Blocking packets in detoured WSASend - blocking

So I have WSASend detoured, and of course can call it to have everything work normally, but some packets (after I analyze them) I want to prevent from being sent, so I can't call the original function. The calling code seems to know something's gone awry no matter what I return.
WSASend is supposed to return 0 when everything went ok. The ironic thing is if I simply return 0 when attempting to block, the calling code seems to be waiting for something, makeing all connections delay and finally close.
code:
int WINAPI myWSASend(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesSent, DWORD dwFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
{
if(lpBuffers->buf[2] == 0x66 && lpBuffers->buf[3] == 0x78)
{
FILE *fp = fopen("party_sploit.txt", "a");
fprintf(fp, "0x7866 catched! len: %lu\n", lpBuffers->len);
for (unsigned int i = 0; i < lpBuffers->len-8; i = i + 8)
{
fprintf(fp,
"%02X %02X %02X %02X %02X %02X %02X %02X"
"\t\t%c %c %c %c %c %c %c %c\n",
static_cast<unsigned char>(lpBuffers->buf[i]),
static_cast<unsigned char>(lpBuffers->buf[i+1]),
static_cast<unsigned char>(lpBuffers->buf[i+2]),
static_cast<unsigned char>(lpBuffers->buf[i+3]),
static_cast<unsigned char>(lpBuffers->buf[i+4]),
static_cast<unsigned char>(lpBuffers->buf[i+5]),
static_cast<unsigned char>(lpBuffers->buf[i+6]),
static_cast<unsigned char>(lpBuffers->buf[i+7]),
(drawable(lpBuffers->buf[i])) ? static_cast<unsigned char>(lpBuffers->buf[i]) : '.',
(drawable(lpBuffers->buf[i+1])) ? static_cast<unsigned char>(lpBuffers->buf[i+1]) : '.',
(drawable(lpBuffers->buf[i+2])) ? static_cast<unsigned char>(lpBuffers->buf[i+2]) : '.',
(drawable(lpBuffers->buf[i+3])) ? static_cast<unsigned char>(lpBuffers->buf[i+3]) : '.',
(drawable(lpBuffers->buf[i+4])) ? static_cast<unsigned char>(lpBuffers->buf[i+4]) : '.',
(drawable(lpBuffers->buf[i+5])) ? static_cast<unsigned char>(lpBuffers->buf[i+5]) : '.',
(drawable(lpBuffers->buf[i+6])) ? static_cast<unsigned char>(lpBuffers->buf[i+6]) : '.',
(drawable(lpBuffers->buf[i+7])) ? static_cast<unsigned char>(lpBuffers->buf[i+7]) : '.'
);
}
fprintf(fp, "\n-------------------------------------------------------------------\n");
fclose(fp);
if(lpBuffers->len < 26)
{
lpNumberOfBytesSent = (LPDWORD)lpBuffers->len;
return 0;
}
else
{
return (oWSASend)(s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags, lpOverlapped, lpCompletionRoutine);
}
}
else
{
//No filtered packet recieved, proceed
return (oWSASend)(s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags, lpOverlapped, lpCompletionRoutine);
}
}

the answere is actually quite simple ... i forgot to dereference the lpNumberOfBytesSent pointer, i also added an if-not-null for security reasons
if(lpBuffers->len != NULL && lpBuffers->len < 26)
{
*lpNumberOfBytesSent = lpBuffers->len;
return 0;
}
else
{
return (oWSASend)(s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags, lpOverlapped, lpCompletionRoutine);
}

Related

Visual Studio Error 2784 : could not deduce template argument for GMP from FLINT

I have a problem running the source code of "homomorphic Simon encryption using YASHE and FV leveled homomorphic cryptosystems" (https://github.com/tlepoint/homomorphic-simon) in Visual Studio 2012.
I'm using FLINT 2.5.2, MPIR 2.7.2, MPFR 1.3.1 and getting numerous errors as follows :
#include "stdafx.h"
#include "FVKey.h"
#include "Sampler.h"
#include <iostream>
#include "arith.h"
#include "timing.h"
#include <string>
/* Static values */
fmpzxx W((fmpzxx(1) << WORDLENGTH)); //error C2678
fmpzxx MASKING((fmpzxx(1) << WORDLENGTH)-fmpzxx(1)); //error C2678
/* Print Key */
std::ostream& operator<<(std::ostream& os, const FVKey& k) {
os << "<FVKey with ell=" << k.ell << " num_slots=" << k.get_num_slots() << " q=" << k.q
<< " t=" << k.t << " sigma_key=" << k.sigmakey << " sigma_err=" << k.sigmaerr
<< ">";
return os;
}
/* Small useful functions */
bool isPowerOfTwo(int n)
{
return (n) && !(n & (n - 1)); //this checks if the integer n is a power of two or not
}
void binaryGen(fmpz_mod_polyxx& f, unsigned degree)
{
for (unsigned i=0; i<=degree; i++)
f.set_coeff(i, fmpzxx((rand()%3)-1));
}
fmpz_mod_polyxx FVKey::BitVectorToPoly(BitVector& m)
{
assert(m.l() == num_slots);
if (!batching || num_slots == 1)
{
fmpz_mod_polyxx pf(q);
for (unsigned i=0; i<m.l(); i++)
pf.set_coeff(i, m[i]);
return pf;
}
else
{
fmpz_mod_polyxx pf(t);
fmpz_mod_polyxx mess(t);
mess.set_coeff(0, m[0]);
pf = mess;
for (unsigned i=1; i<num_slots; i++)
{
mess.set_coeff(0, m[i]);
pf = CRT(pf, mess, i-1);
}
fmpz_mod_polyxx result(q);
result = pf.to<fmpz_polyxx>();
return result;
}
}
unsigned noise_from_poly(const fmpz_mod_polyxx& cval, const fmpzxx &q, unsigned ell)
{
unsigned bitnoise = 0;
fmpzxx coeff;
for (unsigned i=0; i<ell; i++)
{
coeff = (cval.get_coeff(i).to<fmpzxx>()); //error C2893 ,C2228,C2059
if (2*coeff > q) //error C2893, error C2784
coeff = coeff - q; //error C2893, error C2784
if (coeff.sizeinbase(2)>bitnoise)
bitnoise = coeff.sizeinbase(2);
}
return bitnoise;
}
/* Constructor */
FVKey::FVKey(const struct FVParams& params, bool batch)
{
// Initializations
n = params.n;
sigmakey = params.sigmakey;
sigmaerr = params.sigmaerr;
q = params.q;
t = params.t;
logwq = q.sizeinbase(2)/WORDLENGTH+1;
qdivt = q/t; //error C2893, error C2784
qdiv2t = q/(2*t); //error C2784
// Define polynomial modulus
arith_cyclotomic_polynomial(poly._data().inner, n);
phi = new fmpz_mod_polyxx(q);
*phi = poly;
ell = phi->degree();
// Factorize the modulus if batching is set
batching = batch;
num_slots = 1;
if (batching)
{
std::cout << "Factorize the cyclotomic polynomial modulo " << t << std::endl;
fmpz_mod_polyxx phimodt(t);
phimodt = poly;
timing T;
T.start();
factors = new fmpz_mod_poly_factorxx(factor_cantor_zassenhaus(phimodt));
T.stop("Factorize");
unsigned degreeFactors = 0;
for (unsigned i=0; i<factors->size(); i++)
{
degreeFactors += factors->p(i).degree();
}
if (degreeFactors == phimodt.degree() && factors->size()>1)
{
std::cout << "Batching possible on " << factors->size() << " slots" << std::endl;
num_slots = factors->size();
invfactors.resize(num_slots-1, fmpz_mod_polyxx(t));
fmpz_mod_polyxx num(t);
num.set_coeff(0, 1);
for (unsigned i=0; i<num_slots-1; i++)
{
num = num*factors->p(i);
invfactors[i] = num.invmod(factors->p(i+1));
}
}
else
{
std::cout << "Batching impossible" << std::endl;
}
}
// Creating sk/pk
std::cerr << "Creating sk/pk" << std::endl;
a = new fmpz_mod_polyxx(q);
s = new fmpz_mod_polyxx(q);
b = new fmpz_mod_polyxx(q);
for (unsigned i=0; i<ell; i++)
{
fmpzxx coeff = fmpzxx(random.getRandomLong());
for (unsigned j=0; j<q.sizeinbase(2)/64; j++)
coeff = (coeff<<64)+fmpzxx(random.getRandomLong());
a->set_coeff(i, coeff);
}
samplerkey = new Sampler(sigmakey*0.4, 1., &random); // 1/sqrt(2*pi) ~ 0.4
if (sigmakey == 1) binaryGen(*s, ell-1);
else
{
for (unsigned i=0; i<ell; i++)
{
long value = samplerkey->SamplerGaussian();
if (value>=0) s->set_coeff(i, fmpzxx(value));
else s->set_coeff(i, q-fmpzxx(-value));
}
}
samplererr = new Sampler(sigmaerr*0.4, 1., &random); // 1/sqrt(2*pi) ~ 0.4
fmpz_mod_polyxx e(q);
if (sigmaerr == 1) binaryGen(e, ell-1);
else
{
for (unsigned i=0; i<ell; i++)
{
long value = samplererr->SamplerGaussian();
if (value>=0) e.set_coeff(i, fmpzxx(value));
else e.set_coeff(i, q-fmpzxx(-value));
}
}
*b = (-((*a)*(*s)%(*phi)))+e;
// Create evaluation key
gamma.resize(2);
gamma[0].resize(logwq, fmpz_mod_polyxx(q));
for (unsigned i=0; i<logwq; i++)
{
for (unsigned j=0; j<ell; j++)
{
fmpzxx coeff = fmpzxx(random.getRandomLong());
for (unsigned k=0; k<q.sizeinbase(2)/64; k++)
coeff = (coeff<<64)+fmpzxx(random.getRandomLong());
gamma[0][i].set_coeff(j, coeff);
}
}
gamma[1].resize(logwq, fmpz_mod_polyxx(q));
for (unsigned i=0; i<logwq; i++)
{
gamma[1][i] = (*s)*(*s);
for (unsigned j=0; j<i; j++)
gamma[1][i] = gamma[1][i]*W;
fmpz_mod_polyxx e2(q);
if (sigmaerr == 1) binaryGen(e2, ell-1);
else
{
for (unsigned i=0; i<ell; i++)
{
long value = samplererr->SamplerGaussian();
if (value>=0) e2.set_coeff(i, fmpzxx(value));
else e2.set_coeff(i, q-fmpzxx(-value));
}
}
gamma[1][i] += (-(gamma[0][i]*(*s)%(*phi)))+e2;
}
}
Error C2784:
'__gmp_expr,mpir_ui,__gmp_binary_multiplies>>
operator *(const __gmp_expr &,unsigned __int64)' : could not
deduce template argument for 'const __gmp_expr &' from
'int' fvkey.cpp 115 Error C2784:
'__gmp_expr,__gmp_binary_multiplies>>
operator *(unsigned short,const __gmp_expr &)' : could not deduce
template argument for 'const __gmp_expr &' from 'flint::fmpzxx'
Error C2784:
'__gmp_expr,__gmp_binary_minus>> operator -(unsigned short,const __gmp_expr &)' : could not deduce
template argument for 'const __gmp_expr &' from 'const
flint::fmpzxx' fvkey.cpp 116
Error C2784:
'__gmp_expr,__gmp_binary_divides>>
operator /(unsigned short,const __gmp_expr &)' : could not deduce
template argument for 'const __gmp_expr &' from
'flint::fmpzxx' fvkey.cpp 135 Error C2784:
'__gmp_expr,__gmp_binary_multiplies>>
operator *(signed char,const __gmp_expr &)' : could not deduce
template argument for 'const __gmp_expr &' from 'flint::fmpzxx'
fvkey.cpp 115
Error C2784: '__gmp_expr,__gmp_binary_minus>> operator -(long
double,const __gmp_expr &)' : could not deduce template argument
for 'const __gmp_expr &' from 'const flint::fmpzxx'
'flint::fmpzxx' fvkey.cpp 116
Error C2784:
'__gmp_expr,mpir_ui,__gmp_binary_multiplies>>
operator *(const __gmp_expr &,unsigned int)' : could not deduce
template argument for 'const __gmp_expr &' from
'int' 'flint::fmpzxx' fvkey.cpp 115
Error C2678: binary '<<' : no operator found which takes a left-hand
operand of type 'flint::fmpzxx_expression' (or there
is no acceptable conversion) fvkey.cpp 50
I've tried to solve it couple of weeks but still unsuccessfully. Whether it is caused by the "fmpz-conversions.h" from FLINT?
Please help me to figure out what I've done incorrectly. I've uploaded my visual project to http://1drv.ms/1LFpCI4.

How to check that two format strings are compatible?

Examples:
"Something %d" and "Something else %d" // Compatible
"Something %d" and "Something else %f" // Not Compatible
"Something %d" and "Something %d else %d" // Not Compatible
"Something %d and %f" and "Something %2$f and %1$d" // Compatible
I figured there should be some C function for this, but I'm not getting any relevant search results. I mean the compiler is checking that the format string and the arguments match, so the code for checking this is already written. The only question is how I can call it.
I'm using Objective-C, so if there is an Objective-C specific solution that's fine too.
Checking if 2 printf() format strings are compatible is an exercise in format parsing.
C, at least, has no standard run-time compare function such as:
int format_cmp(const char *f1, const char *f2); // Does not exist
Formats like "%d %f" and "%i %e" are obviously compatible in that both expect an int and float/double. Note: float are promoted to double as short and signed char are promoted to int.
Formats "%*.*f" and "%i %d %e" are compatible, but not obvious: both expect an int,int and float/double.
Formats "%hhd" and "%d" both expect an int, even though the first will have it values cast to signed char before printing.
Formats "%d" and "%u" are not compatible. Even though many systems will behaved as hoped. Note: Typically char will promote to int.
Formats "%d" and "%ld" are not strictly compatible. On a 32-bit system there are equivalent, but not in general. Of course code can be altered to accommodate this. OTOH "%lf" and "%f" are compatible due to the usual argument promotions of float to double.
Formats "%lu" and "%zu" may be compatible, but that depends on the implementation of unsigned long and size_t. Additions to code could allow this or related equivalences.
Some combinations of modifiers and specifiers are not defined like "%zp". The following does not dis-allow such esoteric combinations - but does compare them.
Modifiers like "$" are extensions to standard C and are not implemented in the following.
The compatibility test for printf() differs from scanf().
#include <ctype.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
typedef enum {
type_none,
type_int,
type_unsigned,
type_float,
type_charpointer,
type_voidpointer,
type_intpointer,
type_unknown,
type_type_N = 0xFFFFFF
} type_type;
typedef struct {
const char *format;
int int_queue;
type_type type;
} format_T;
static void format_init(format_T *state, const char *format);
static type_type format_get(format_T *state);
static void format_next(format_T *state);
void format_init(format_T *state, const char *format) {
state->format = format;
state->int_queue = 0;
state->type = type_none;
format_next(state);
}
type_type format_get(format_T *state) {
if (state->int_queue > 0) {
return type_int;
}
return state->type;
}
const char *seek_flag(const char *format) {
while (strchr("-+ #0", *format) != NULL)
format++;
return format;
}
const char *seek_width(const char *format, int *int_queue) {
*int_queue = 0;
if (*format == '*') {
format++;
(*int_queue)++;
} else {
while (isdigit((unsigned char ) *format))
format++;
}
if (*format == '.') {
if (*format == '*') {
format++;
(*int_queue)++;
} else {
while (isdigit((unsigned char ) *format))
format++;
}
}
return format;
}
const char *seek_mod(const char *format, int *mod) {
*mod = 0;
if (format[0] == 'h' && format[1] == 'h') {
format += 2;
} else if (format[0] == 'l' && format[1] == 'l') {
*mod = ('l' << CHAR_BIT) + 'l';
format += 2;
} else if (strchr("ljztL", *format)) {
*mod = *format;
format++;
} else if (strchr("h", *format)) {
format++;
}
return format;
}
const char *seek_specifier(const char *format, int mod, type_type *type) {
if (strchr("di", *format)) {
*type = type_int;
format++;
} else if (strchr("ouxX", *format)) {
*type = type_unsigned;
format++;
} else if (strchr("fFeEgGaA", *format)) {
if (mod == 'l') mod = 0;
*type = type_float;
format++;
} else if (strchr("c", *format)) {
*type = type_int;
format++;
} else if (strchr("s", *format)) {
*type = type_charpointer;
format++;
} else if (strchr("p", *format)) {
*type = type_voidpointer;
format++;
} else if (strchr("n", *format)) {
*type = type_intpointer;
format++;
} else {
*type = type_unknown;
exit(1);
}
*type |= mod << CHAR_BIT; // Bring in modifier
return format;
}
void format_next(format_T *state) {
if (state->int_queue > 0) {
state->int_queue--;
return;
}
while (*state->format) {
if (state->format[0] == '%') {
state->format++;
if (state->format[0] == '%') {
state->format++;
continue;
}
state->format = seek_flag(state->format);
state->format = seek_width(state->format, &state->int_queue);
int mod;
state->format = seek_mod(state->format, &mod);
state->format = seek_specifier(state->format, mod, &state->type);
return;
} else {
state->format++;
}
}
state->type = type_none;
}
// 0 Compatible
// 1 Not Compatible
// 2 Not Comparable
int format_cmp(const char *f1, const char *f2) {
format_T state1;
format_init(&state1, f1);
format_T state2;
format_init(&state2, f2);
while (format_get(&state1) == format_get(&state2)) {
if (format_get(&state1) == type_none)
return 0;
if (format_get(&state1) == type_unknown)
return 2;
format_next(&state1);
format_next(&state2);
}
if (format_get(&state1) == type_unknown)
return 2;
if (format_get(&state2) == type_unknown)
return 2;
return 1;
}
Note: only minimal testing done. Lots of additional considerations could be added.
Known shortcomings: hh,h,l,ll,j,z,t modifiers with n. l with s,c.
[Edit]
OP comments about security concerns. This changes the nature of the post and the compare from an equality one to a security one. I'd imagine that one of the patterns (A) would be a reference pattern and the next (B) would be the test. The test would be "is B at least as secure as A?". Example A = "%.20s" and B1 = "%.19s", B2 = "%.20s", B3 = "%.21s". B1 and B2 both pass the security test as they do not extract more the 20 char. B3 is a problem as it goes pass the reference limit of 20 char. Further any non-width qualified with %s %[ %c is a security problem - in the reference or test pattern. This answer's code does not address this issue.
As mentioned, code does not yet handle modifiers with "%n".
[2018 edit]
Concerning "Formats "%d" and "%u" are not compatible.": This is for values to be printed in general. For values in the [0..INT_MAX] range, either format may work per C11dr ยง6.5.2.2 6.
My understanding of what you want, is that, you basically want a method which can look at two strings and detect if they both have the same types of values in them. Or something a long those lines.... If so, then try this (or something along the lines of this):
-(int)checkCompatible:(NSString *)string_1 :(NSString *)string_2 {
// Separate the string into single elements.
NSArray *stringArray_1 = [string_1 componentsSeparatedByString:#" "];
NSArray *stringArray_2 = [string_2 componentsSeparatedByString:#" "];
// Store only the numbers for comparison in a new array.
NSMutableArray *numbers_1 = [[NSMutableArray alloc] init];
NSMutableArray *numbers_2 = [[NSMutableArray alloc] init];
// Make sure the for loop below, runs for the appropriate
// number of cycles depending on which array is bigger.
int loopMax = 0;
if ([stringArray_1 count] > [stringArray_2 count]) {
loopMax = (int)[stringArray_1 count];
}
else {
loopMax = (int)[stringArray_2 count];
}
// Now go through the stringArray's and store only the
// numbers in the mutable array's. This will be used
// during the comparison stage.
for (int loop = 0; loop < loopMax; loop++) {
NSCharacterSet *notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if (loop < [stringArray_1 count]) {
if ([[stringArray_1 objectAtindex:loop] rangeOfCharacterFromSet:notDigits].location == NSNotFound) {
// String consists only of the digits 0 through 9.
[numbers_1 addObject:[stringArray_1 objectAtindex:loop]];
}
}
if (loop < [stringArray_2 count]) {
if ([[stringArray_2 objectAtindex:loop] rangeOfCharacterFromSet:notDigits].location == NSNotFound) {
// String consists only of the digits 0 through 9.
[numbers_2 addObject:[stringArray_2 objectAtindex:loop]];
}
}
}
// Now look through the mutable array's
// and perform the type comparison,.
if ([numbers_1 count] != [numbers_2 count]) {
// One of the two strings has more numbers
// than the other, so they are NOT compatible.
return 1;
}
else {
// Both string have the same number of numbers
// numbers so lets go through them to make
// sure the numbers are of the same type.
for (int loop = 0; loop < [numbers_1 count]; loop++) {
// Check to see if the number in the current array index
// is a float or an integer. All the numbers in the array have
// to be the SAME type, in order for the strings to be compatible.
BOOL check_float_1 = [[NSScanner scannerWithString:[numbers_1 objectAtindex:loop]] scanFloat:nil];
BOOL check_int_1 = [[NSScanner scannerWithString:[numbers_1 objectAtindex:loop]] scanInt:nil];
BOOL check_float_2 = [[NSScanner scannerWithString:[numbers_2 objectAtindex:loop]] scanFloat:nil];
BOOL check_int_2 = [[NSScanner scannerWithString:[numbers_2 objectAtindex:loop]] scanInt:nil];
if (check_float_1 == YES) {
if (check_float_2 == NO) {
return 1;
}
}
else if (check_int_1 == YES) {
if (check_int_2 == NO) {
return 1;
}
}
else {
// Error of some sort......
return 1;
}
}
// All the numbers in the strings are of the same
// type (otherwise we would NOT have reached
// this point). Therefore the strings are compatible.
return 0;
}
}

Reading .hex file in VHDL

I'm trying to read an intel .hex file using the following VHDL code snippet. My synthesizer is having a problem with the part of the code that is supposed to check for and discard the ':' character at the start of a line. The synthesis tool gives this error "Call to procedure without body" (line marked with comment). I have never seen this error and don't know what it means. Is there a solution for this error (or an alternate way to discard the ':' character)?
function Load_Data(constant x: in integer) return ROM_Data is
use std.textio.all;
use ieee.std_logic_textio.all;
file ROMFILE: TEXT open READ_MODE is "IIU_Code.hex";
variable newline: line;
variable newchar: character;
variable newbyte: std_logic_vector(7 downto 0);
variable newword: std_logic_vector(15 downto 0);
variable NextAddr, ByteCount: integer;
variable NewROM: ROM_Data := (others => (others => '0'));
variable valid: boolean := True;
begin
while (valid) loop
readline(ROMFILE, newline);
read(newline,newchar,valid); --ERROR HERE!!!
if (newchar = ':') and (valid = True) then
hread(newline,newbyte);
ByteCount := to_integer(unsigned(newbyte));
hread(newline,newword);
NextAddr := to_integer(unsigned(newword));
hread(newline,newbyte);
if newbyte = X"01" then --check for EOF marker
valid := False;
end if;
for i in 1 to ByteCount loop
hread(newline,newbyte);
NewROM(NextAddr) := newbyte;
NextAddr := NextAddr + 1;
end loop;
end if;
end loop;
file_close(ROMFILE);
return NewROM;
end;
In lieu of trying to force synthesis to initialize ROM from a file I've been known to write C programs that convert data for models to constants, in this case by generating entity/architecture pairs:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_VECTOR 512
void rom_header (rom_name,array_size)
char *rom_name;
int array_size;
{
printf("library ieee;\nuse ieee.std_logic_1164.all;\n");
printf("\nentity %s is\n port (\n",rom_name);
printf("\tindex:\t\tin integer range 0 to %d;\n",array_size*8-1);
printf("\tOE:\t\tin std_logic;\n");
printf("\toutput:\t\tout std_logic_vector (7 downto 0)\n");
printf(" );\nend ;\n");
printf("\narchitecture behave of %s is\n\n",rom_name);
printf(" subtype bytestring is bit_vector( 7 downto 0);\n");
printf(" type bytestream is array (0 to %d) of bytestring;\n\n",
array_size*8-1);
printf(" constant byte_array:\tbytestream := (\n\t ");
}
void rom_tail() {
printf(" begin\n\n");
printf(" output <= To_StdLogicVector(byte_array(index)) ");
printf("when OE = '1' else\n");
printf(" (others => 'Z') ");
printf("when OE = '0' else\n");
printf(" (others => 'X');\n");
printf("\n\nend behave;\n\n");
}
int main (argc,argv)
int argc;
char *argv[];
{
extern char *optarg;
extern int optind, opterr;
extern int getopt();
char *infile;
char key_vector[MAX_VECTOR][16];
char plain_vector[MAX_VECTOR][16];
char cipher_vector[MAX_VECTOR][16];
char testinput[2047];
char testkey[17];
char testplain[17];
char testcipher[17];
int encrypt[MAX_VECTOR];
int i;
int len;
int testcount = 0;
int totalcount = 0;
int linenumber = 0;
int vector = 0;
int encode = 1;
while ( (i=getopt(argc,argv,"i:")) != -1 ) {
switch (i) {
case 'i':
infile = optarg;
if((freopen(optarg,"r",stdin)) == NULL) {
fprintf(stderr,"ERROR:%s, can't open %s for input\n",
argv[0],optarg);
exit(-1);
}
break;
case '?':
fprintf(stderr,"usage: %s [-i infile] \n",argv[0]);
fprintf(stderr,"\ngenerates VHDL arrays for DES test vectors:\n");
fprintf(stderr,"\tcipher_vector.vhdl\n");
fprintf(stderr,"\tencrypt_vector.vhdl\n");
fprintf(stderr,"\tkey_vector.vhdl\n");
fprintf(stderr,"\tplain_vector.vhdl\n");
exit (-1);
break;
}
}
while (fgets(testinput,(sizeof testinput) -1, stdin) != NULL ) {
linenumber++;
if ( strncmp(testinput,"encrypt",7) == 0) { /* mode = encode */
encode = 1;
fprintf(stderr,"%s",testinput);
}
else
if ( strncmp(testinput,"decrypt",7) == 0) { /* mode = decode */
fprintf(stderr,"%s",testinput);
encode = 0;
}
else
if ( strncmp(testinput," ",1) == 0) { /* key, plain & cipher */
testcount++;
len = sscanf(testinput,"%s%s%s*", testkey, testplain, testcipher);
if (len != 3) {
fprintf(stderr,"ERROR: %s, wrong vector count, line %d\n",
argv[0], linenumber);
exit(-1);
}
else if (strlen(testkey) != 16) {
fprintf(stderr,"ERROR: %s wrong byte count testkey, line %d\n",
argv[0],linenumber);
exit(-1);
}
else if (strlen(testplain) != 16) {
fprintf(stderr,"ERROR: %s wrong byte count testplain, line %d\n",
argv[0],linenumber);
exit(-1);
}
else if (strlen(testcipher) != 16) {
fprintf(stderr,"ERROR: %s wrong byte count testcipher, line %d\n",
argv[0],linenumber);
exit(-1);
}
else {
encrypt[vector] = encode;
strncpy( key_vector[vector], testkey,16);
strncpy( plain_vector[vector], testplain,16);
strncpy(cipher_vector[vector],testcipher,16);
for ( i = 0; i < 16; i++) {
if ( !isxdigit(key_vector[vector][i]) ||
!isxdigit(plain_vector[vector][i]) ||
!isxdigit(cipher_vector[vector][i]) ) {
fprintf(stderr,"ERROR: %s, Vector: %d contains nonhex\n",
argv[0], vector+1);
fprintf(stderr,"\t%s\n",testinput);
exit(-1);
}
}
}
vector++;
if (vector == MAX_VECTOR) {
fprintf(stderr,"%s: Maximum number of vectors = %d\n",
argv[0],MAX_VECTOR);
exit(0);
}
}
else { /* nothing but eyewash */
if ( testcount ) {
fprintf(stderr," %d test vectors\n",testcount);
totalcount +=testcount;
testcount = 0;
}
}
}
fprintf(stderr," Total: %d test vectors\n",totalcount);
if (freopen("key_vector.vhdl","w",stdout) == NULL){
fprintf(stderr,"ERROR: %s can write to key_vector.vhdl\n",argv[0]);
exit (-1);
}
rom_header("key_vector",totalcount);
for(vector = 0; vector < totalcount; vector++) {
for ( i = 0; i <= 15; i++) {
if ( !(i & 1)) {
printf("x\"%c",key_vector[vector][i]);
}
else {
if ( i < 15) {
printf("%c\",",key_vector[vector][i]);
}
else {
printf("%c\"",key_vector[vector][i]); // no comma
}
}
}
if (vector != totalcount-1)
printf(",\n\t ");
else
printf("\n\t);\n");
}
rom_tail();
if (freopen("plain_vector.vhdl","w",stdout) == NULL){
fprintf(stderr,"ERROR: %s can write to plain_vector.vhdl\n",argv[0]);
exit (-1);
}
rom_header("plain_vector",totalcount);
for(vector = 0; vector < totalcount; vector++) {
for ( i = 0; i <= 15; i++) {
if ( !(i & 1)) {
printf("x\"%c",plain_vector[vector][i]);
}
else {
if ( i < 15) {
printf("%c\",",plain_vector[vector][i]);
}
else {
printf("%c\"",plain_vector[vector][i]); // no comma
}
}
}
if (vector != totalcount-1)
printf(",\n\t ");
else
printf("\n\t);\n");
}
rom_tail();
if (freopen("cipher_vector.vhdl","w",stdout) == NULL){
fprintf(stderr,"ERROR: %s can write to cipher_vector.vhdl\n",argv[0]);
exit (-1);
}
rom_header("cipher_vector",totalcount);
for(vector = 0; vector < totalcount; vector++) {
for ( i = 0; i <= 15; i++) {
if ( !(i & 1)) {
printf("x\"%c",cipher_vector[vector][i]);
}
else {
if ( i < 15) {
printf("%c\",",cipher_vector[vector][i]);
}
else {
printf("%c\"",cipher_vector[vector][i]); // no comma
}
}
}
if (vector != totalcount-1)
printf(",\n\t ");
else
printf("\n\t);\n");
}
rom_tail();
if (freopen("encrypt_vector.vhdl","w",stdout) == NULL){
fprintf(stderr,"ERROR: %s can write to encrypt_vector.vhdl\n",argv[0]);
exit (-1);
}
printf("library ieee;\nuse ieee.std_logic_1164.all;\n");
printf("\nentity encrypt_vector is\n port (\n");
printf("\tindex:\t\tin integer range 0 to %d;\n",totalcount-1);
printf("\toutput:\t\tout std_logic\n");
printf(" );\nend ;\n");
printf("\narchitecture behave of encrypt_vector is\n\n");
printf(" constant bit_array:\tstd_logic_vector(0 to %d) := (\n\t ",
totalcount-1);
i = 0;
for(vector = 0; vector < totalcount; vector++) {
printf("'%1d'",encrypt[vector]);i++;
if ((i == 16) && (vector != totalcount-1)) {
printf(",\n\t ");
i = 0;
}
else if (vector == totalcount-1)
printf("\n\t);\n");
else
printf(",");
}
printf(" begin\n\n");
printf(" output <= bit_array(index);");
printf("\n\nend behave;\n\n");
exit (0);
}
You could also do this for packages or even subprograms.
This particular conversion software uses a form of valid vectors preceded by an encryption mode switch and having a first column space, providing hex values of the right string length:
#
encrypt
#
0101010101010101 95F8A5E5DD31D900 8000000000000000
0101010101010101 DD7F121CA5015619 4000000000000000
0101010101010101 2E8653104F3834EA 2000000000000000
0101010101010101 4BD388FF6CD81D4F 1000000000000000
0101010101010101 20B9E767B2FB1456 0800000000000000
0101010101010101 55579380D77138EF 0400000000000000
0101010101010101 6CC5DEFAAF04512F 0200000000000000
#
It's the test vectors for a byte wide interfaced DES chip, and in this case only used in a test bench. There's nothing stopping you from embedding something like you want.
This little C program is quite old but I believe I updated it recently enough it would compile and run, it spits out several different 'vector' files for the test bench based on what the values are used for. It wants the input file to be concluded with a comment line ('#' in the first column), followed by a newline.
So the message here is don't count directly on your synthesis tools to initialize data (unless they handle it with explicitly supported routines).
See How to synthesis a rom and load initial data into it ?, for a hint thread in Xilinx, otherwise noting you haven't specified target platform.
addendum
The questioner has been forthcoming with additional information in comments, wherein automated software has exhorted us to Please avoid extended discussions in comments.
The target is a Microsemi ProASIC3, which also prompted another look at the provided Load_Data function, whose input argument x doesn't show up in the function body. While that indicates the author may have been battling uphill restrictions trying to read a file.
Looking at Microsemi's web site we see that a ProASIC3 can have an embedded 1K bit FLASHROM, which may or may not be the ROM in question. I'm an ASIC designer from way back and can appreciate the size range of these devices, intended for among other uses System on Chip applications. You'd expect the vendor would be able to supply information on how to use the FLASHROM.
For other ROM purposes in lieu of vendor supplied method of loading ROM it would seem that creating a synthesis compatible method of embedding an array of constants is in order (analogous to what's shown in the C programming example).
One characteristic of Read Only Memory in programmable devices is that the values are typically included as part of device programming.

Use of blocks in Objective-C

const char *sentence = "He was not in the cab at the time.";
printf("\"%s\" has %d spaces\n", sentence, (int) ^ {
int i = 0;
int countSpaces = 0;
while (sentence[i] != '\0') {
if (sentence[i] == 0x20) {
countSpaces++;
}
i++;
}
return countSpaces;
});
This code simply counts the white space in a string, but for some reason it says 1606416608 spaces rather than 8. I'm not exactly sure what is going wrong, so thanks for any help!
You're passing the actual block to printf, not the result of the block. Instead, try
const char *sentence = "He was not in the cab at the time.";
printf("\"%s\" has %d spaces\n", sentence, (int) ^ {
int i = 0;
int countSpaces = 0;
while (sentence[i] != '\0') {
if (sentence[i] == 0x20) {
countSpaces++;
}
i++;
}
return countSpaces;
}()); // <-- note the extra parentheses here, indicating that you're calling the block

Getting the MAC Address in Objective-C

How do I get the MAC address of the computer in Objective-C? I was using the following code but it started crashing once I switched to using the LLVM compiler. Can anyone tell me how to fix this code or give me new code that works? I found a way to do it in 10.6+, but I need it to work with 10.5 too.
void GetHWAddresses()
{
struct ifconf ifc;
struct ifreq *ifr;
int i, sockfd;
char buffer[BUFFERSIZE], *cp, *cplim;
char temp[80];
for (i=0; i<MAXADDRS; ++i)
{
hw_addrs[i] = NULL;
}
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0)
{
perror("socket failed");
return;
}
ifc.ifc_len = BUFFERSIZE;
ifc.ifc_buf = buffer;
if (ioctl(sockfd, SIOCGIFCONF, (char *)&ifc) < 0)
{
perror("ioctl error");
close(sockfd);
return;
}
ifr = ifc.ifc_req;
cplim = buffer + ifc.ifc_len;
for (cp=buffer; cp < cplim; )
{
ifr = (struct ifreq *)cp;
if (ifr->ifr_addr.sa_family == AF_LINK)
{
struct sockaddr_dl *sdl = (struct sockaddr_dl *)&ifr->ifr_addr;
int a,b,c,d,e,f;
int i;
strcpy(temp, (char *)ether_ntoa(LLADDR(sdl)));
sscanf(temp, "%x:%x:%x:%x:%x:%x", &a, &b, &c, &d, &e, &f);
sprintf(temp, "%02X:%02X:%02X:%02X:%02X:%02X",a,b,c,d,e,f);
for (i=0; i<MAXADDRS; ++i)
{
if ((if_names[i] != NULL) && (strcmp(ifr->ifr_name, if_names[i]) == 0))
{
if (hw_addrs[i] == NULL)
{
hw_addrs[i] = (char *)malloc(strlen(temp)+1);
strcpy(hw_addrs[i], temp);
break;
}
}
}
}
cp += sizeof(ifr->ifr_name) + max(sizeof(ifr->ifr_addr), ifr->ifr_addr.sa_len);
}
close(sockfd);
}
Apple actually have some example code for getting the MAC address from the IO registry