code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
/* -*- c -*- */
#include "tests/filesys/seq-test.h"
#include "tests/main.h"
static char buf[TEST_SIZE];
static size_t
return_block_size (void)
{
return BLOCK_SIZE;
}
void
test_main (void)
{
seq_test ("noodle",
buf, sizeof buf, sizeof buf,
return_block_size, NULL);
}
| 10cm | trunk/10cm/pintos/src/tests/filesys/base/seq-block.inc | C | oos | 301 |
/* Writes out the content of a fairly large file in random order,
then reads it back in random order to verify that it was
written properly. */
#define BLOCK_SIZE 512
#define TEST_SIZE (512 * 150)
#include "tests/filesys/base/random.inc"
| 10cm | trunk/10cm/pintos/src/tests/filesys/base/lg-random.c | C | oos | 245 |
package Algorithm::Diff;
# Skip to first "=head" line for documentation.
use strict;
use integer; # see below in _replaceNextLargerWith() for mod to make
# if you don't use this
use vars qw( $VERSION @EXPORT_OK );
$VERSION = 1.19_01;
# ^ ^^ ^^-- Incremented at will
# | \+----- Incremented for non-trivial changes to features
# \-------- Incremented for fundamental changes
require Exporter;
*import = \&Exporter::import;
@EXPORT_OK = qw(
prepare LCS LCDidx LCS_length
diff sdiff compact_diff
traverse_sequences traverse_balanced
);
# McIlroy-Hunt diff algorithm
# Adapted from the Smalltalk code of Mario I. Wolczko, <mario@wolczko.com>
# by Ned Konz, perl@bike-nomad.com
# Updates by Tye McQueen, http://perlmonks.org/?node=tye
# Create a hash that maps each element of $aCollection to the set of
# positions it occupies in $aCollection, restricted to the elements
# within the range of indexes specified by $start and $end.
# The fourth parameter is a subroutine reference that will be called to
# generate a string to use as a key.
# Additional parameters, if any, will be passed to this subroutine.
#
# my $hashRef = _withPositionsOfInInterval( \@array, $start, $end, $keyGen );
sub _withPositionsOfInInterval
{
my $aCollection = shift; # array ref
my $start = shift;
my $end = shift;
my $keyGen = shift;
my %d;
my $index;
for ( $index = $start ; $index <= $end ; $index++ )
{
my $element = $aCollection->[$index];
my $key = &$keyGen( $element, @_ );
if ( exists( $d{$key} ) )
{
unshift ( @{ $d{$key} }, $index );
}
else
{
$d{$key} = [$index];
}
}
return wantarray ? %d : \%d;
}
# Find the place at which aValue would normally be inserted into the
# array. If that place is already occupied by aValue, do nothing, and
# return undef. If the place does not exist (i.e., it is off the end of
# the array), add it to the end, otherwise replace the element at that
# point with aValue. It is assumed that the array's values are numeric.
# This is where the bulk (75%) of the time is spent in this module, so
# try to make it fast!
sub _replaceNextLargerWith
{
my ( $array, $aValue, $high ) = @_;
$high ||= $#$array;
# off the end?
if ( $high == -1 || $aValue > $array->[-1] )
{
push ( @$array, $aValue );
return $high + 1;
}
# binary search for insertion point...
my $low = 0;
my $index;
my $found;
while ( $low <= $high )
{
$index = ( $high + $low ) / 2;
# $index = int(( $high + $low ) / 2); # without 'use integer'
$found = $array->[$index];
if ( $aValue == $found )
{
return undef;
}
elsif ( $aValue > $found )
{
$low = $index + 1;
}
else
{
$high = $index - 1;
}
}
# now insertion point is in $low.
$array->[$low] = $aValue; # overwrite next larger
return $low;
}
# This method computes the longest common subsequence in $a and $b.
# Result is array or ref, whose contents is such that
# $a->[ $i ] == $b->[ $result[ $i ] ]
# foreach $i in ( 0 .. $#result ) if $result[ $i ] is defined.
# An additional argument may be passed; this is a hash or key generating
# function that should return a string that uniquely identifies the given
# element. It should be the case that if the key is the same, the elements
# will compare the same. If this parameter is undef or missing, the key
# will be the element as a string.
# By default, comparisons will use "eq" and elements will be turned into keys
# using the default stringizing operator '""'.
# Additional parameters, if any, will be passed to the key generation
# routine.
sub _longestCommonSubsequence
{
my $a = shift; # array ref or hash ref
my $b = shift; # array ref or hash ref
my $counting = shift; # scalar
my $keyGen = shift; # code ref
my $compare; # code ref
if ( ref($a) eq 'HASH' )
{ # prepared hash must be in $b
my $tmp = $b;
$b = $a;
$a = $tmp;
}
# Check for bogus (non-ref) argument values
if ( !ref($a) || !ref($b) )
{
my @callerInfo = caller(1);
die 'error: must pass array or hash references to ' . $callerInfo[3];
}
# set up code refs
# Note that these are optimized.
if ( !defined($keyGen) ) # optimize for strings
{
$keyGen = sub { $_[0] };
$compare = sub { my ( $a, $b ) = @_; $a eq $b };
}
else
{
$compare = sub {
my $a = shift;
my $b = shift;
&$keyGen( $a, @_ ) eq &$keyGen( $b, @_ );
};
}
my ( $aStart, $aFinish, $matchVector ) = ( 0, $#$a, [] );
my ( $prunedCount, $bMatches ) = ( 0, {} );
if ( ref($b) eq 'HASH' ) # was $bMatches prepared for us?
{
$bMatches = $b;
}
else
{
my ( $bStart, $bFinish ) = ( 0, $#$b );
# First we prune off any common elements at the beginning
while ( $aStart <= $aFinish
and $bStart <= $bFinish
and &$compare( $a->[$aStart], $b->[$bStart], @_ ) )
{
$matchVector->[ $aStart++ ] = $bStart++;
$prunedCount++;
}
# now the end
while ( $aStart <= $aFinish
and $bStart <= $bFinish
and &$compare( $a->[$aFinish], $b->[$bFinish], @_ ) )
{
$matchVector->[ $aFinish-- ] = $bFinish--;
$prunedCount++;
}
# Now compute the equivalence classes of positions of elements
$bMatches =
_withPositionsOfInInterval( $b, $bStart, $bFinish, $keyGen, @_ );
}
my $thresh = [];
my $links = [];
my ( $i, $ai, $j, $k );
for ( $i = $aStart ; $i <= $aFinish ; $i++ )
{
$ai = &$keyGen( $a->[$i], @_ );
if ( exists( $bMatches->{$ai} ) )
{
$k = 0;
for $j ( @{ $bMatches->{$ai} } )
{
# optimization: most of the time this will be true
if ( $k and $thresh->[$k] > $j and $thresh->[ $k - 1 ] < $j )
{
$thresh->[$k] = $j;
}
else
{
$k = _replaceNextLargerWith( $thresh, $j, $k );
}
# oddly, it's faster to always test this (CPU cache?).
if ( defined($k) )
{
$links->[$k] =
[ ( $k ? $links->[ $k - 1 ] : undef ), $i, $j ];
}
}
}
}
if (@$thresh)
{
return $prunedCount + @$thresh if $counting;
for ( my $link = $links->[$#$thresh] ; $link ; $link = $link->[0] )
{
$matchVector->[ $link->[1] ] = $link->[2];
}
}
elsif ($counting)
{
return $prunedCount;
}
return wantarray ? @$matchVector : $matchVector;
}
sub traverse_sequences
{
my $a = shift; # array ref
my $b = shift; # array ref
my $callbacks = shift || {};
my $keyGen = shift;
my $matchCallback = $callbacks->{'MATCH'} || sub { };
my $discardACallback = $callbacks->{'DISCARD_A'} || sub { };
my $finishedACallback = $callbacks->{'A_FINISHED'};
my $discardBCallback = $callbacks->{'DISCARD_B'} || sub { };
my $finishedBCallback = $callbacks->{'B_FINISHED'};
my $matchVector = _longestCommonSubsequence( $a, $b, 0, $keyGen, @_ );
# Process all the lines in @$matchVector
my $lastA = $#$a;
my $lastB = $#$b;
my $bi = 0;
my $ai;
for ( $ai = 0 ; $ai <= $#$matchVector ; $ai++ )
{
my $bLine = $matchVector->[$ai];
if ( defined($bLine) ) # matched
{
&$discardBCallback( $ai, $bi++, @_ ) while $bi < $bLine;
&$matchCallback( $ai, $bi++, @_ );
}
else
{
&$discardACallback( $ai, $bi, @_ );
}
}
# The last entry (if any) processed was a match.
# $ai and $bi point just past the last matching lines in their sequences.
while ( $ai <= $lastA or $bi <= $lastB )
{
# last A?
if ( $ai == $lastA + 1 and $bi <= $lastB )
{
if ( defined($finishedACallback) )
{
&$finishedACallback( $lastA, @_ );
$finishedACallback = undef;
}
else
{
&$discardBCallback( $ai, $bi++, @_ ) while $bi <= $lastB;
}
}
# last B?
if ( $bi == $lastB + 1 and $ai <= $lastA )
{
if ( defined($finishedBCallback) )
{
&$finishedBCallback( $lastB, @_ );
$finishedBCallback = undef;
}
else
{
&$discardACallback( $ai++, $bi, @_ ) while $ai <= $lastA;
}
}
&$discardACallback( $ai++, $bi, @_ ) if $ai <= $lastA;
&$discardBCallback( $ai, $bi++, @_ ) if $bi <= $lastB;
}
return 1;
}
sub traverse_balanced
{
my $a = shift; # array ref
my $b = shift; # array ref
my $callbacks = shift || {};
my $keyGen = shift;
my $matchCallback = $callbacks->{'MATCH'} || sub { };
my $discardACallback = $callbacks->{'DISCARD_A'} || sub { };
my $discardBCallback = $callbacks->{'DISCARD_B'} || sub { };
my $changeCallback = $callbacks->{'CHANGE'};
my $matchVector = _longestCommonSubsequence( $a, $b, 0, $keyGen, @_ );
# Process all the lines in match vector
my $lastA = $#$a;
my $lastB = $#$b;
my $bi = 0;
my $ai = 0;
my $ma = -1;
my $mb;
while (1)
{
# Find next match indices $ma and $mb
do {
$ma++;
} while(
$ma <= $#$matchVector
&& !defined $matchVector->[$ma]
);
last if $ma > $#$matchVector; # end of matchVector?
$mb = $matchVector->[$ma];
# Proceed with discard a/b or change events until
# next match
while ( $ai < $ma || $bi < $mb )
{
if ( $ai < $ma && $bi < $mb )
{
# Change
if ( defined $changeCallback )
{
&$changeCallback( $ai++, $bi++, @_ );
}
else
{
&$discardACallback( $ai++, $bi, @_ );
&$discardBCallback( $ai, $bi++, @_ );
}
}
elsif ( $ai < $ma )
{
&$discardACallback( $ai++, $bi, @_ );
}
else
{
# $bi < $mb
&$discardBCallback( $ai, $bi++, @_ );
}
}
# Match
&$matchCallback( $ai++, $bi++, @_ );
}
while ( $ai <= $lastA || $bi <= $lastB )
{
if ( $ai <= $lastA && $bi <= $lastB )
{
# Change
if ( defined $changeCallback )
{
&$changeCallback( $ai++, $bi++, @_ );
}
else
{
&$discardACallback( $ai++, $bi, @_ );
&$discardBCallback( $ai, $bi++, @_ );
}
}
elsif ( $ai <= $lastA )
{
&$discardACallback( $ai++, $bi, @_ );
}
else
{
# $bi <= $lastB
&$discardBCallback( $ai, $bi++, @_ );
}
}
return 1;
}
sub prepare
{
my $a = shift; # array ref
my $keyGen = shift; # code ref
# set up code ref
$keyGen = sub { $_[0] } unless defined($keyGen);
return scalar _withPositionsOfInInterval( $a, 0, $#$a, $keyGen, @_ );
}
sub LCS
{
my $a = shift; # array ref
my $b = shift; # array ref or hash ref
my $matchVector = _longestCommonSubsequence( $a, $b, 0, @_ );
my @retval;
my $i;
for ( $i = 0 ; $i <= $#$matchVector ; $i++ )
{
if ( defined( $matchVector->[$i] ) )
{
push ( @retval, $a->[$i] );
}
}
return wantarray ? @retval : \@retval;
}
sub LCS_length
{
my $a = shift; # array ref
my $b = shift; # array ref or hash ref
return _longestCommonSubsequence( $a, $b, 1, @_ );
}
sub LCSidx
{
my $a= shift @_;
my $b= shift @_;
my $match= _longestCommonSubsequence( $a, $b, 0, @_ );
my @am= grep defined $match->[$_], 0..$#$match;
my @bm= @{$match}[@am];
return \@am, \@bm;
}
sub compact_diff
{
my $a= shift @_;
my $b= shift @_;
my( $am, $bm )= LCSidx( $a, $b, @_ );
my @cdiff;
my( $ai, $bi )= ( 0, 0 );
push @cdiff, $ai, $bi;
while( 1 ) {
while( @$am && $ai == $am->[0] && $bi == $bm->[0] ) {
shift @$am;
shift @$bm;
++$ai, ++$bi;
}
push @cdiff, $ai, $bi;
last if ! @$am;
$ai = $am->[0];
$bi = $bm->[0];
push @cdiff, $ai, $bi;
}
push @cdiff, 0+@$a, 0+@$b
if $ai < @$a || $bi < @$b;
return wantarray ? @cdiff : \@cdiff;
}
sub diff
{
my $a = shift; # array ref
my $b = shift; # array ref
my $retval = [];
my $hunk = [];
my $discard = sub {
push @$hunk, [ '-', $_[0], $a->[ $_[0] ] ];
};
my $add = sub {
push @$hunk, [ '+', $_[1], $b->[ $_[1] ] ];
};
my $match = sub {
push @$retval, $hunk
if 0 < @$hunk;
$hunk = []
};
traverse_sequences( $a, $b,
{ MATCH => $match, DISCARD_A => $discard, DISCARD_B => $add }, @_ );
&$match();
return wantarray ? @$retval : $retval;
}
sub sdiff
{
my $a = shift; # array ref
my $b = shift; # array ref
my $retval = [];
my $discard = sub { push ( @$retval, [ '-', $a->[ $_[0] ], "" ] ) };
my $add = sub { push ( @$retval, [ '+', "", $b->[ $_[1] ] ] ) };
my $change = sub {
push ( @$retval, [ 'c', $a->[ $_[0] ], $b->[ $_[1] ] ] );
};
my $match = sub {
push ( @$retval, [ 'u', $a->[ $_[0] ], $b->[ $_[1] ] ] );
};
traverse_balanced(
$a,
$b,
{
MATCH => $match,
DISCARD_A => $discard,
DISCARD_B => $add,
CHANGE => $change,
},
@_
);
return wantarray ? @$retval : $retval;
}
########################################
my $Root= __PACKAGE__;
package Algorithm::Diff::_impl;
use strict;
sub _Idx() { 0 } # $me->[_Idx]: Ref to array of hunk indices
# 1 # $me->[1]: Ref to first sequence
# 2 # $me->[2]: Ref to second sequence
sub _End() { 3 } # $me->[_End]: Diff between forward and reverse pos
sub _Same() { 4 } # $me->[_Same]: 1 if pos 1 contains unchanged items
sub _Base() { 5 } # $me->[_Base]: Added to range's min and max
sub _Pos() { 6 } # $me->[_Pos]: Which hunk is currently selected
sub _Off() { 7 } # $me->[_Off]: Offset into _Idx for current position
sub _Min() { -2 } # Added to _Off to get min instead of max+1
sub Die
{
require Carp;
Carp::confess( @_ );
}
sub _ChkPos
{
my( $me )= @_;
return if $me->[_Pos];
my $meth= ( caller(1) )[3];
Die( "Called $meth on 'reset' object" );
}
sub _ChkSeq
{
my( $me, $seq )= @_;
return $seq + $me->[_Off]
if 1 == $seq || 2 == $seq;
my $meth= ( caller(1) )[3];
Die( "$meth: Invalid sequence number ($seq); must be 1 or 2" );
}
sub getObjPkg
{
my( $us )= @_;
return ref $us if ref $us;
return $us . "::_obj";
}
sub new
{
my( $us, $seq1, $seq2, $opts ) = @_;
my @args;
for( $opts->{keyGen} ) {
push @args, $_ if $_;
}
for( $opts->{keyGenArgs} ) {
push @args, @$_ if $_;
}
my $cdif= Algorithm::Diff::compact_diff( $seq1, $seq2, @args );
my $same= 1;
if( 0 == $cdif->[2] && 0 == $cdif->[3] ) {
$same= 0;
splice @$cdif, 0, 2;
}
my @obj= ( $cdif, $seq1, $seq2 );
$obj[_End] = (1+@$cdif)/2;
$obj[_Same] = $same;
$obj[_Base] = 0;
my $me = bless \@obj, $us->getObjPkg();
$me->Reset( 0 );
return $me;
}
sub Reset
{
my( $me, $pos )= @_;
$pos= int( $pos || 0 );
$pos += $me->[_End]
if $pos < 0;
$pos= 0
if $pos < 0 || $me->[_End] <= $pos;
$me->[_Pos]= $pos || !1;
$me->[_Off]= 2*$pos - 1;
return $me;
}
sub Base
{
my( $me, $base )= @_;
my $oldBase= $me->[_Base];
$me->[_Base]= 0+$base if defined $base;
return $oldBase;
}
sub Copy
{
my( $me, $pos, $base )= @_;
my @obj= @$me;
my $you= bless \@obj, ref($me);
$you->Reset( $pos ) if defined $pos;
$you->Base( $base );
return $you;
}
sub Next {
my( $me, $steps )= @_;
$steps= 1 if ! defined $steps;
if( $steps ) {
my $pos= $me->[_Pos];
my $new= $pos + $steps;
$new= 0 if $pos && $new < 0;
$me->Reset( $new )
}
return $me->[_Pos];
}
sub Prev {
my( $me, $steps )= @_;
$steps= 1 if ! defined $steps;
my $pos= $me->Next(-$steps);
$pos -= $me->[_End] if $pos;
return $pos;
}
sub Diff {
my( $me )= @_;
$me->_ChkPos();
return 0 if $me->[_Same] == ( 1 & $me->[_Pos] );
my $ret= 0;
my $off= $me->[_Off];
for my $seq ( 1, 2 ) {
$ret |= $seq
if $me->[_Idx][ $off + $seq + _Min ]
< $me->[_Idx][ $off + $seq ];
}
return $ret;
}
sub Min {
my( $me, $seq, $base )= @_;
$me->_ChkPos();
my $off= $me->_ChkSeq($seq);
$base= $me->[_Base] if !defined $base;
return $base + $me->[_Idx][ $off + _Min ];
}
sub Max {
my( $me, $seq, $base )= @_;
$me->_ChkPos();
my $off= $me->_ChkSeq($seq);
$base= $me->[_Base] if !defined $base;
return $base + $me->[_Idx][ $off ] -1;
}
sub Range {
my( $me, $seq, $base )= @_;
$me->_ChkPos();
my $off = $me->_ChkSeq($seq);
if( !wantarray ) {
return $me->[_Idx][ $off ]
- $me->[_Idx][ $off + _Min ];
}
$base= $me->[_Base] if !defined $base;
return ( $base + $me->[_Idx][ $off + _Min ] )
.. ( $base + $me->[_Idx][ $off ] - 1 );
}
sub Items {
my( $me, $seq )= @_;
$me->_ChkPos();
my $off = $me->_ChkSeq($seq);
if( !wantarray ) {
return $me->[_Idx][ $off ]
- $me->[_Idx][ $off + _Min ];
}
return
@{$me->[$seq]}[
$me->[_Idx][ $off + _Min ]
.. ( $me->[_Idx][ $off ] - 1 )
];
}
sub Same {
my( $me )= @_;
$me->_ChkPos();
return wantarray ? () : 0
if $me->[_Same] != ( 1 & $me->[_Pos] );
return $me->Items(1);
}
my %getName;
BEGIN {
%getName= (
same => \&Same,
diff => \&Diff,
base => \&Base,
min => \&Min,
max => \&Max,
range=> \&Range,
items=> \&Items, # same thing
);
}
sub Get
{
my $me= shift @_;
$me->_ChkPos();
my @value;
for my $arg ( @_ ) {
for my $word ( split ' ', $arg ) {
my $meth;
if( $word !~ /^(-?\d+)?([a-zA-Z]+)([12])?$/
|| not $meth= $getName{ lc $2 }
) {
Die( $Root, ", Get: Invalid request ($word)" );
}
my( $base, $name, $seq )= ( $1, $2, $3 );
push @value, scalar(
4 == length($name)
? $meth->( $me )
: $meth->( $me, $seq, $base )
);
}
}
if( wantarray ) {
return @value;
} elsif( 1 == @value ) {
return $value[0];
}
Die( 0+@value, " values requested from ",
$Root, "'s Get in scalar context" );
}
my $Obj= getObjPkg($Root);
no strict 'refs';
for my $meth ( qw( new getObjPkg ) ) {
*{$Root."::".$meth} = \&{$meth};
*{$Obj ."::".$meth} = \&{$meth};
}
for my $meth ( qw(
Next Prev Reset Copy Base Diff
Same Items Range Min Max Get
_ChkPos _ChkSeq
) ) {
*{$Obj."::".$meth} = \&{$meth};
}
1;
__END__
=head1 NAME
Algorithm::Diff - Compute `intelligent' differences between two files / lists
=head1 SYNOPSIS
require Algorithm::Diff;
# This example produces traditional 'diff' output:
my $diff = Algorithm::Diff->new( \@seq1, \@seq2 );
$diff->Base( 1 ); # Return line numbers, not indices
while( $diff->Next() ) {
next if $diff->Same();
my $sep = '';
if( ! $diff->Items(2) ) {
sprintf "%d,%dd%d\n",
$diff->Get(qw( Min1 Max1 Max2 ));
} elsif( ! $diff->Items(1) ) {
sprint "%da%d,%d\n",
$diff->Get(qw( Max1 Min2 Max2 ));
} else {
$sep = "---\n";
sprintf "%d,%dc%d,%d\n",
$diff->Get(qw( Min1 Max1 Min2 Max2 ));
}
print "< $_" for $diff->Items(1);
print $sep;
print "> $_" for $diff->Items(2);
}
# Alternate interfaces:
use Algorithm::Diff qw(
LCS LCS_length LCSidx
diff sdiff compact_diff
traverse_sequences traverse_balanced );
@lcs = LCS( \@seq1, \@seq2 );
$lcsref = LCS( \@seq1, \@seq2 );
$count = LCS_length( \@seq1, \@seq2 );
( $seq1idxref, $seq2idxref ) = LCSidx( \@seq1, \@seq2 );
# Complicated interfaces:
@diffs = diff( \@seq1, \@seq2 );
@sdiffs = sdiff( \@seq1, \@seq2 );
@cdiffs = compact_diff( \@seq1, \@seq2 );
traverse_sequences(
\@seq1,
\@seq2,
{ MATCH => \&callback1,
DISCARD_A => \&callback2,
DISCARD_B => \&callback3,
},
\&key_generator,
@extra_args,
);
traverse_balanced(
\@seq1,
\@seq2,
{ MATCH => \&callback1,
DISCARD_A => \&callback2,
DISCARD_B => \&callback3,
CHANGE => \&callback4,
},
\&key_generator,
@extra_args,
);
=head1 INTRODUCTION
(by Mark-Jason Dominus)
I once read an article written by the authors of C<diff>; they said
that they worked very hard on the algorithm until they found the
right one.
I think what they ended up using (and I hope someone will correct me,
because I am not very confident about this) was the `longest common
subsequence' method. In the LCS problem, you have two sequences of
items:
a b c d f g h j q z
a b c d e f g i j k r x y z
and you want to find the longest sequence of items that is present in
both original sequences in the same order. That is, you want to find
a new sequence I<S> which can be obtained from the first sequence by
deleting some items, and from the secend sequence by deleting other
items. You also want I<S> to be as long as possible. In this case I<S>
is
a b c d f g j z
From there it's only a small step to get diff-like output:
e h i k q r x y
+ - + + - + + +
This module solves the LCS problem. It also includes a canned function
to generate C<diff>-like output.
It might seem from the example above that the LCS of two sequences is
always pretty obvious, but that's not always the case, especially when
the two sequences have many repeated elements. For example, consider
a x b y c z p d q
a b c a x b y c z
A naive approach might start by matching up the C<a> and C<b> that
appear at the beginning of each sequence, like this:
a x b y c z p d q
a b c a b y c z
This finds the common subsequence C<a b c z>. But actually, the LCS
is C<a x b y c z>:
a x b y c z p d q
a b c a x b y c z
or
a x b y c z p d q
a b c a x b y c z
=head1 USAGE
(See also the README file and several example
scripts include with this module.)
This module now provides an object-oriented interface that uses less
memory and is easier to use than most of the previous procedural
interfaces. It also still provides several exportable functions. We'll
deal with these in ascending order of difficulty: C<LCS>,
C<LCS_length>, C<LCSidx>, OO interface, C<prepare>, C<diff>, C<sdiff>,
C<traverse_sequences>, and C<traverse_balanced>.
=head2 C<LCS>
Given references to two lists of items, LCS returns an array containing
their longest common subsequence. In scalar context, it returns a
reference to such a list.
@lcs = LCS( \@seq1, \@seq2 );
$lcsref = LCS( \@seq1, \@seq2 );
C<LCS> may be passed an optional third parameter; this is a CODE
reference to a key generation function. See L</KEY GENERATION
FUNCTIONS>.
@lcs = LCS( \@seq1, \@seq2, \&keyGen, @args );
$lcsref = LCS( \@seq1, \@seq2, \&keyGen, @args );
Additional parameters, if any, will be passed to the key generation
routine.
=head2 C<LCS_length>
This is just like C<LCS> except it only returns the length of the
longest common subsequence. This provides a performance gain of about
9% compared to C<LCS>.
=head2 C<LCSidx>
Like C<LCS> except it returns references to two arrays. The first array
contains the indices into @seq1 where the LCS items are located. The
second array contains the indices into @seq2 where the LCS items are located.
Therefore, the following three lists will contain the same values:
my( $idx1, $idx2 ) = LCSidx( \@seq1, \@seq2 );
my @list1 = @seq1[ @$idx1 ];
my @list2 = @seq2[ @$idx2 ];
my @list3 = LCS( \@seq1, \@seq2 );
=head2 C<new>
$diff = Algorithm::Diffs->new( \@seq1, \@seq2 );
$diff = Algorithm::Diffs->new( \@seq1, \@seq2, \%opts );
C<new> computes the smallest set of additions and deletions necessary
to turn the first sequence into the second and compactly records them
in the object.
You use the object to iterate over I<hunks>, where each hunk represents
a contiguous section of items which should be added, deleted, replaced,
or left unchanged.
=over 4
The following summary of all of the methods looks a lot like Perl code
but some of the symbols have different meanings:
[ ] Encloses optional arguments
: Is followed by the default value for an optional argument
| Separates alternate return results
Method summary:
$obj = Algorithm::Diff->new( \@seq1, \@seq2, [ \%opts ] );
$pos = $obj->Next( [ $count : 1 ] );
$revPos = $obj->Prev( [ $count : 1 ] );
$obj = $obj->Reset( [ $pos : 0 ] );
$copy = $obj->Copy( [ $pos, [ $newBase ] ] );
$oldBase = $obj->Base( [ $newBase ] );
Note that all of the following methods C<die> if used on an object that
is "reset" (not currently pointing at any hunk).
$bits = $obj->Diff( );
@items|$cnt = $obj->Same( );
@items|$cnt = $obj->Items( $seqNum );
@idxs |$cnt = $obj->Range( $seqNum, [ $base ] );
$minIdx = $obj->Min( $seqNum, [ $base ] );
$maxIdx = $obj->Max( $seqNum, [ $base ] );
@values = $obj->Get( @names );
Passing in C<undef> for an optional argument is always treated the same
as if no argument were passed in.
=item C<Next>
$pos = $diff->Next(); # Move forward 1 hunk
$pos = $diff->Next( 2 ); # Move forward 2 hunks
$pos = $diff->Next(-5); # Move backward 5 hunks
C<Next> moves the object to point at the next hunk. The object starts
out "reset", which means it isn't pointing at any hunk. If the object
is reset, then C<Next()> moves to the first hunk.
C<Next> returns a true value iff the move didn't go past the last hunk.
So C<Next(0)> will return true iff the object is not reset.
Actually, C<Next> returns the object's new position, which is a number
between 1 and the number of hunks (inclusive), or returns a false value.
=item C<Prev>
C<Prev($N)> is almost identical to C<Next(-$N)>; it moves to the $Nth
previous hunk. On a 'reset' object, C<Prev()> [and C<Next(-1)>] move
to the last hunk.
The position returned by C<Prev> is relative to the I<end> of the
hunks; -1 for the last hunk, -2 for the second-to-last, etc.
=item C<Reset>
$diff->Reset(); # Reset the object's position
$diff->Reset($pos); # Move to the specified hunk
$diff->Reset(1); # Move to the first hunk
$diff->Reset(-1); # Move to the last hunk
C<Reset> returns the object, so, for example, you could use
C<< $diff->Reset()->Next(-1) >> to get the number of hunks.
=item C<Copy>
$copy = $diff->Copy( $newPos, $newBase );
C<Copy> returns a copy of the object. The copy and the orignal object
share most of their data, so making copies takes very little memory.
The copy maintains its own position (separate from the original), which
is the main purpose of copies. It also maintains its own base.
By default, the copy's position starts out the same as the original
object's position. But C<Copy> takes an optional first argument to set the
new position, so the following three snippets are equivalent:
$copy = $diff->Copy($pos);
$copy = $diff->Copy();
$copy->Reset($pos);
$copy = $diff->Copy()->Reset($pos);
C<Copy> takes an optional second argument to set the base for
the copy. If you wish to change the base of the copy but leave
the position the same as in the original, here are two
equivalent ways:
$copy = $diff->Copy();
$copy->Base( 0 );
$copy = $diff->Copy(undef,0);
Here are two equivalent way to get a "reset" copy:
$copy = $diff->Copy(0);
$copy = $diff->Copy()->Reset();
=item C<Diff>
$bits = $obj->Diff();
C<Diff> returns a true value iff the current hunk contains items that are
different between the two sequences. It actually returns one of the
follow 4 values:
=over 4
=item 3
C<3==(1|2)>. This hunk contains items from @seq1 and the items
from @seq2 that should replace them. Both sequence 1 and 2
contain changed items so both the 1 and 2 bits are set.
=item 2
This hunk only contains items from @seq2 that should be inserted (not
items from @seq1). Only sequence 2 contains changed items so only the 2
bit is set.
=item 1
This hunk only contains items from @seq1 that should be deleted (not
items from @seq2). Only sequence 1 contains changed items so only the 1
bit is set.
=item 0
This means that the items in this hunk are the same in both sequences.
Neither sequence 1 nor 2 contain changed items so neither the 1 nor the
2 bits are set.
=back
=item C<Same>
C<Same> returns a true value iff the current hunk contains items that
are the same in both sequences. It actually returns the list of items
if they are the same or an emty list if they aren't. In a scalar
context, it returns the size of the list.
=item C<Items>
$count = $diff->Items(2);
@items = $diff->Items($seqNum);
C<Items> returns the (number of) items from the specified sequence that
are part of the current hunk.
If the current hunk contains only insertions, then
C<< $diff->Items(1) >> will return an empty list (0 in a scalar conext).
If the current hunk contains only deletions, then C<< $diff->Items(2) >>
will return an empty list (0 in a scalar conext).
If the hunk contains replacements, then both C<< $diff->Items(1) >> and
C<< $diff->Items(2) >> will return different, non-empty lists.
Otherwise, the hunk contains identical items and all of the following
will return the same lists:
@items = $diff->Items(1);
@items = $diff->Items(2);
@items = $diff->Same();
=item C<Range>
$count = $diff->Range( $seqNum );
@indices = $diff->Range( $seqNum );
@indices = $diff->Range( $seqNum, $base );
C<Range> is like C<Items> except that it returns a list of I<indices> to
the items rather than the items themselves. By default, the index of
the first item (in each sequence) is 0 but this can be changed by
calling the C<Base> method. So, by default, the following two snippets
return the same lists:
@list = $diff->Items(2);
@list = @seq2[ $diff->Range(2) ];
You can also specify the base to use as the second argument. So the
following two snippets I<always> return the same lists:
@list = $diff->Items(1);
@list = @seq1[ $diff->Range(1,0) ];
=item C<Base>
$curBase = $diff->Base();
$oldBase = $diff->Base($newBase);
C<Base> sets and/or returns the current base (usually 0 or 1) that is
used when you request range information. The base defaults to 0 so
that range information is returned as array indices. You can set the
base to 1 if you want to report traditional line numbers instead.
=item C<Min>
$min1 = $diff->Min(1);
$min = $diff->Min( $seqNum, $base );
C<Min> returns the first value that C<Range> would return (given the
same arguments) or returns C<undef> if C<Range> would return an empty
list.
=item C<Max>
C<Max> returns the last value that C<Range> would return or C<undef>.
=item C<Get>
( $n, $x, $r ) = $diff->Get(qw( min1 max1 range1 ));
@values = $diff->Get(qw( 0min2 1max2 range2 same base ));
C<Get> returns one or more scalar values. You pass in a list of the
names of the values you want returned. Each name must match one of the
following regexes:
/^(-?\d+)?(min|max)[12]$/i
/^(range[12]|same|diff|base)$/i
The 1 or 2 after a name says which sequence you want the information
for (and where allowed, it is required). The optional number before
"min" or "max" is the base to use. So the following equalities hold:
$diff->Get('min1') == $diff->Min(1)
$diff->Get('0min2') == $diff->Min(2,0)
Using C<Get> in a scalar context when you've passed in more than one
name is a fatal error (C<die> is called).
=back
=head2 C<prepare>
Given a reference to a list of items, C<prepare> returns a reference
to a hash which can be used when comparing this sequence to other
sequences with C<LCS> or C<LCS_length>.
$prep = prepare( \@seq1 );
for $i ( 0 .. 10_000 )
{
@lcs = LCS( $prep, $seq[$i] );
# do something useful with @lcs
}
C<prepare> may be passed an optional third parameter; this is a CODE
reference to a key generation function. See L</KEY GENERATION
FUNCTIONS>.
$prep = prepare( \@seq1, \&keyGen );
for $i ( 0 .. 10_000 )
{
@lcs = LCS( $seq[$i], $prep, \&keyGen );
# do something useful with @lcs
}
Using C<prepare> provides a performance gain of about 50% when calling LCS
many times compared with not preparing.
=head2 C<diff>
@diffs = diff( \@seq1, \@seq2 );
$diffs_ref = diff( \@seq1, \@seq2 );
C<diff> computes the smallest set of additions and deletions necessary
to turn the first sequence into the second, and returns a description
of these changes. The description is a list of I<hunks>; each hunk
represents a contiguous section of items which should be added,
deleted, or replaced. (Hunks containing unchanged items are not
included.)
The return value of C<diff> is a list of hunks, or, in scalar context, a
reference to such a list. If there are no differences, the list will be
empty.
Here is an example. Calling C<diff> for the following two sequences:
a b c e h j l m n p
b c d e f j k l m r s t
would produce the following list:
(
[ [ '-', 0, 'a' ] ],
[ [ '+', 2, 'd' ] ],
[ [ '-', 4, 'h' ],
[ '+', 4, 'f' ] ],
[ [ '+', 6, 'k' ] ],
[ [ '-', 8, 'n' ],
[ '-', 9, 'p' ],
[ '+', 9, 'r' ],
[ '+', 10, 's' ],
[ '+', 11, 't' ] ],
)
There are five hunks here. The first hunk says that the C<a> at
position 0 of the first sequence should be deleted (C<->). The second
hunk says that the C<d> at position 2 of the second sequence should
be inserted (C<+>). The third hunk says that the C<h> at position 4
of the first sequence should be removed and replaced with the C<f>
from position 4 of the second sequence. And so on.
C<diff> may be passed an optional third parameter; this is a CODE
reference to a key generation function. See L</KEY GENERATION
FUNCTIONS>.
Additional parameters, if any, will be passed to the key generation
routine.
=head2 C<sdiff>
@sdiffs = sdiff( \@seq1, \@seq2 );
$sdiffs_ref = sdiff( \@seq1, \@seq2 );
C<sdiff> computes all necessary components to show two sequences
and their minimized differences side by side, just like the
Unix-utility I<sdiff> does:
same same
before | after
old < -
- > new
It returns a list of array refs, each pointing to an array of
display instructions. In scalar context it returns a reference
to such a list. If there are no differences, the list will have one
entry per item, each indicating that the item was unchanged.
Display instructions consist of three elements: A modifier indicator
(C<+>: Element added, C<->: Element removed, C<u>: Element unmodified,
C<c>: Element changed) and the value of the old and new elements, to
be displayed side-by-side.
An C<sdiff> of the following two sequences:
a b c e h j l m n p
b c d e f j k l m r s t
results in
( [ '-', 'a', '' ],
[ 'u', 'b', 'b' ],
[ 'u', 'c', 'c' ],
[ '+', '', 'd' ],
[ 'u', 'e', 'e' ],
[ 'c', 'h', 'f' ],
[ 'u', 'j', 'j' ],
[ '+', '', 'k' ],
[ 'u', 'l', 'l' ],
[ 'u', 'm', 'm' ],
[ 'c', 'n', 'r' ],
[ 'c', 'p', 's' ],
[ '+', '', 't' ],
)
C<sdiff> may be passed an optional third parameter; this is a CODE
reference to a key generation function. See L</KEY GENERATION
FUNCTIONS>.
Additional parameters, if any, will be passed to the key generation
routine.
=head2 C<compact_diff>
C<compact_diff> is much like C<sdiff> except it returns a much more
compact description consisting of just one flat list of indices. An
example helps explain the format:
my @a = qw( a b c e h j l m n p );
my @b = qw( b c d e f j k l m r s t );
@cdiff = compact_diff( \@a, \@b );
# Returns:
# @a @b @a @b
# start start values values
( 0, 0, # =
0, 0, # a !
1, 0, # b c = b c
3, 2, # ! d
3, 3, # e = e
4, 4, # f ! h
5, 5, # j = j
6, 6, # ! k
6, 7, # l m = l m
8, 9, # n p ! r s t
10, 12, #
);
The 0th, 2nd, 4th, etc. entries are all indices into @seq1 (@a in the
above example) indicating where a hunk begins. The 1st, 3rd, 5th, etc.
entries are all indices into @seq2 (@b in the above example) indicating
where the same hunk begins.
So each pair of indices (except the last pair) describes where a hunk
begins (in each sequence). Since each hunk must end at the item just
before the item that starts the next hunk, the next pair of indices can
be used to determine where the hunk ends.
So, the first 4 entries (0..3) describe the first hunk. Entries 0 and 1
describe where the first hunk begins (and so are always both 0).
Entries 2 and 3 describe where the next hunk begins, so subtracting 1
from each tells us where the first hunk ends. That is, the first hunk
contains items C<$diff[0]> through C<$diff[2] - 1> of the first sequence
and contains items C<$diff[1]> through C<$diff[3] - 1> of the second
sequence.
In other words, the first hunk consists of the following two lists of items:
# 1st pair 2nd pair
# of indices of indices
@list1 = @a[ $cdiff[0] .. $cdiff[2]-1 ];
@list2 = @b[ $cdiff[1] .. $cdiff[3]-1 ];
# Hunk start Hunk end
Note that the hunks will always alternate between those that are part of
the LCS (those that contain unchanged items) and those that contain
changes. This means that all we need to be told is whether the first
hunk is a 'same' or 'diff' hunk and we can determine which of the other
hunks contain 'same' items or 'diff' items.
By convention, we always make the first hunk contain unchanged items.
So the 1st, 3rd, 5th, etc. hunks (all odd-numbered hunks if you start
counting from 1) all contain unchanged items. And the 2nd, 4th, 6th,
etc. hunks (all even-numbered hunks if you start counting from 1) all
contain changed items.
Since @a and @b don't begin with the same value, the first hunk in our
example is empty (otherwise we'd violate the above convention). Note
that the first 4 index values in our example are all zero. Plug these
values into our previous code block and we get:
@hunk1a = @a[ 0 .. 0-1 ];
@hunk1b = @b[ 0 .. 0-1 ];
And C<0..-1> returns the empty list.
Move down one pair of indices (2..5) and we get the offset ranges for
the second hunk, which contains changed items.
Since C<@diff[2..5]> contains (0,0,1,0) in our example, the second hunk
consists of these two lists of items:
@hunk2a = @a[ $cdiff[2] .. $cdiff[4]-1 ];
@hunk2b = @b[ $cdiff[3] .. $cdiff[5]-1 ];
# or
@hunk2a = @a[ 0 .. 1-1 ];
@hunk2b = @b[ 0 .. 0-1 ];
# or
@hunk2a = @a[ 0 .. 0 ];
@hunk2b = @b[ 0 .. -1 ];
# or
@hunk2a = ( 'a' );
@hunk2b = ( );
That is, we would delete item 0 ('a') from @a.
Since C<@diff[4..7]> contains (1,0,3,2) in our example, the third hunk
consists of these two lists of items:
@hunk3a = @a[ $cdiff[4] .. $cdiff[6]-1 ];
@hunk3a = @b[ $cdiff[5] .. $cdiff[7]-1 ];
# or
@hunk3a = @a[ 1 .. 3-1 ];
@hunk3a = @b[ 0 .. 2-1 ];
# or
@hunk3a = @a[ 1 .. 2 ];
@hunk3a = @b[ 0 .. 1 ];
# or
@hunk3a = qw( b c );
@hunk3a = qw( b c );
Note that this third hunk contains unchanged items as our convention demands.
You can continue this process until you reach the last two indices,
which will always be the number of items in each sequence. This is
required so that subtracting one from each will give you the indices to
the last items in each sequence.
=head2 C<traverse_sequences>
C<traverse_sequences> used to be the most general facility provided by
this module (the new OO interface is more powerful and much easier to
use).
Imagine that there are two arrows. Arrow A points to an element of
sequence A, and arrow B points to an element of the sequence B.
Initially, the arrows point to the first elements of the respective
sequences. C<traverse_sequences> will advance the arrows through the
sequences one element at a time, calling an appropriate user-specified
callback function before each advance. It willadvance the arrows in
such a way that if there are equal elements C<$A[$i]> and C<$B[$j]>
which are equal and which are part of the LCS, there will be some moment
during the execution of C<traverse_sequences> when arrow A is pointing
to C<$A[$i]> and arrow B is pointing to C<$B[$j]>. When this happens,
C<traverse_sequences> will call the C<MATCH> callback function and then
it will advance both arrows.
Otherwise, one of the arrows is pointing to an element of its sequence
that is not part of the LCS. C<traverse_sequences> will advance that
arrow and will call the C<DISCARD_A> or the C<DISCARD_B> callback,
depending on which arrow it advanced. If both arrows point to elements
that are not part of the LCS, then C<traverse_sequences> will advance
one of them and call the appropriate callback, but it is not specified
which it will call.
The arguments to C<traverse_sequences> are the two sequences to
traverse, and a hash which specifies the callback functions, like this:
traverse_sequences(
\@seq1, \@seq2,
{ MATCH => $callback_1,
DISCARD_A => $callback_2,
DISCARD_B => $callback_3,
}
);
Callbacks for MATCH, DISCARD_A, and DISCARD_B are invoked with at least
the indices of the two arrows as their arguments. They are not expected
to return any values. If a callback is omitted from the table, it is
not called.
Callbacks for A_FINISHED and B_FINISHED are invoked with at least the
corresponding index in A or B.
If arrow A reaches the end of its sequence, before arrow B does,
C<traverse_sequences> will call the C<A_FINISHED> callback when it
advances arrow B, if there is such a function; if not it will call
C<DISCARD_B> instead. Similarly if arrow B finishes first.
C<traverse_sequences> returns when both arrows are at the ends of their
respective sequences. It returns true on success and false on failure.
At present there is no way to fail.
C<traverse_sequences> may be passed an optional fourth parameter; this
is a CODE reference to a key generation function. See L</KEY GENERATION
FUNCTIONS>.
Additional parameters, if any, will be passed to the key generation function.
If you want to pass additional parameters to your callbacks, but don't
need a custom key generation function, you can get the default by
passing undef:
traverse_sequences(
\@seq1, \@seq2,
{ MATCH => $callback_1,
DISCARD_A => $callback_2,
DISCARD_B => $callback_3,
},
undef, # default key-gen
$myArgument1,
$myArgument2,
$myArgument3,
);
C<traverse_sequences> does not have a useful return value; you are
expected to plug in the appropriate behavior with the callback
functions.
=head2 C<traverse_balanced>
C<traverse_balanced> is an alternative to C<traverse_sequences>. It
uses a different algorithm to iterate through the entries in the
computed LCS. Instead of sticking to one side and showing element changes
as insertions and deletions only, it will jump back and forth between
the two sequences and report I<changes> occurring as deletions on one
side followed immediatly by an insertion on the other side.
In addition to the C<DISCARD_A>, C<DISCARD_B>, and C<MATCH> callbacks
supported by C<traverse_sequences>, C<traverse_balanced> supports
a C<CHANGE> callback indicating that one element got C<replaced> by another:
traverse_balanced(
\@seq1, \@seq2,
{ MATCH => $callback_1,
DISCARD_A => $callback_2,
DISCARD_B => $callback_3,
CHANGE => $callback_4,
}
);
If no C<CHANGE> callback is specified, C<traverse_balanced>
will map C<CHANGE> events to C<DISCARD_A> and C<DISCARD_B> actions,
therefore resulting in a similar behaviour as C<traverse_sequences>
with different order of events.
C<traverse_balanced> might be a bit slower than C<traverse_sequences>,
noticable only while processing huge amounts of data.
The C<sdiff> function of this module
is implemented as call to C<traverse_balanced>.
C<traverse_balanced> does not have a useful return value; you are expected to
plug in the appropriate behavior with the callback functions.
=head1 KEY GENERATION FUNCTIONS
Most of the functions accept an optional extra parameter. This is a
CODE reference to a key generating (hashing) function that should return
a string that uniquely identifies a given element. It should be the
case that if two elements are to be considered equal, their keys should
be the same (and the other way around). If no key generation function
is provided, the key will be the element as a string.
By default, comparisons will use "eq" and elements will be turned into keys
using the default stringizing operator '""'.
Where this is important is when you're comparing something other than
strings. If it is the case that you have multiple different objects
that should be considered to be equal, you should supply a key
generation function. Otherwise, you have to make sure that your arrays
contain unique references.
For instance, consider this example:
package Person;
sub new
{
my $package = shift;
return bless { name => '', ssn => '', @_ }, $package;
}
sub clone
{
my $old = shift;
my $new = bless { %$old }, ref($old);
}
sub hash
{
return shift()->{'ssn'};
}
my $person1 = Person->new( name => 'Joe', ssn => '123-45-6789' );
my $person2 = Person->new( name => 'Mary', ssn => '123-47-0000' );
my $person3 = Person->new( name => 'Pete', ssn => '999-45-2222' );
my $person4 = Person->new( name => 'Peggy', ssn => '123-45-9999' );
my $person5 = Person->new( name => 'Frank', ssn => '000-45-9999' );
If you did this:
my $array1 = [ $person1, $person2, $person4 ];
my $array2 = [ $person1, $person3, $person4, $person5 ];
Algorithm::Diff::diff( $array1, $array2 );
everything would work out OK (each of the objects would be converted
into a string like "Person=HASH(0x82425b0)" for comparison).
But if you did this:
my $array1 = [ $person1, $person2, $person4 ];
my $array2 = [ $person1, $person3, $person4->clone(), $person5 ];
Algorithm::Diff::diff( $array1, $array2 );
$person4 and $person4->clone() (which have the same name and SSN)
would be seen as different objects. If you wanted them to be considered
equivalent, you would have to pass in a key generation function:
my $array1 = [ $person1, $person2, $person4 ];
my $array2 = [ $person1, $person3, $person4->clone(), $person5 ];
Algorithm::Diff::diff( $array1, $array2, \&Person::hash );
This would use the 'ssn' field in each Person as a comparison key, and
so would consider $person4 and $person4->clone() as equal.
You may also pass additional parameters to the key generation function
if you wish.
=head1 ERROR CHECKING
If you pass these routines a non-reference and they expect a reference,
they will die with a message.
=head1 AUTHOR
This version released by Tye McQueen (http://perlmonks.org/?node=tye).
=head1 LICENSE
Parts Copyright (c) 2000-2004 Ned Konz. All rights reserved.
Parts by Tye McQueen.
This program is free software; you can redistribute it and/or modify it
under the same terms as Perl.
=head1 MAILING LIST
Mark-Jason still maintains a mailing list. To join a low-volume mailing
list for announcements related to diff and Algorithm::Diff, send an
empty mail message to mjd-perl-diff-request@plover.com.
=head1 CREDITS
Versions through 0.59 (and much of this documentation) were written by:
Mark-Jason Dominus, mjd-perl-diff@plover.com
This version borrows some documentation and routine names from
Mark-Jason's, but Diff.pm's code was completely replaced.
This code was adapted from the Smalltalk code of Mario Wolczko
<mario@wolczko.com>, which is available at
ftp://st.cs.uiuc.edu/pub/Smalltalk/MANCHESTER/manchester/4.0/diff.st
C<sdiff> and C<traverse_balanced> were written by Mike Schilli
<m@perlmeister.com>.
The algorithm is that described in
I<A Fast Algorithm for Computing Longest Common Subsequences>,
CACM, vol.20, no.5, pp.350-353, May 1977, with a few
minor improvements to improve the speed.
Much work was done by Ned Konz (perl@bike-nomad.com).
The OO interface and some other changes are by Tye McQueen.
=cut
| 10cm | trunk/10cm/pintos/src/tests/Algorithm/Diff.pm | Perl | oos | 51,093 |
#! /usr/bin/perl
use strict;
use warnings;
@ARGV == 3 || die;
my ($src_dir, $results_file, $grading_file) = @ARGV;
# Read pass/file verdicts from $results_file.
open (RESULTS, '<', $results_file) || die "$results_file: open: $!\n";
my (%verdicts, %verdict_counts);
while (<RESULTS>) {
my ($verdict, $test) = /^(pass|FAIL) (.*)$/ or die;
$verdicts{$test} = $verdict eq 'pass';
}
close RESULTS;
my (@failures);
my (@overall, @rubrics, @summary);
my ($pct_actual, $pct_possible) = (0, 0);
# Read grading file.
my (@items);
open (GRADING, '<', $grading_file) || die "$grading_file: open: $!\n";
while (<GRADING>) {
s/#.*//;
next if /^\s*$/;
my ($max_pct, $rubric_suffix) = /^\s*(\d+(?:\.\d+)?)%\t(.*)/ or die;
my ($dir) = $rubric_suffix =~ /^(.*)\//;
my ($rubric_file) = "$src_dir/$rubric_suffix";
open (RUBRIC, '<', $rubric_file) or die "$rubric_file: open: $!\n";
# Rubric file must begin with title line.
my $title = <RUBRIC>;
chomp $title;
$title =~ s/:$// or die;
$title .= " ($rubric_suffix):";
push (@rubrics, $title);
my ($score, $possible) = (0, 0);
my ($cnt, $passed) = (0, 0);
my ($was_score) = 0;
while (<RUBRIC>) {
chomp;
push (@rubrics, "\t$_"), next if /^-/;
push (@rubrics, ""), next if /^\s*$/;
my ($poss, $name) = /^(\d+)\t(.*)$/ or die;
my ($test) = "$dir/$name";
my ($points) = 0;
if (!defined $verdicts{$test}) {
push (@overall, "warning: $test not tested, assuming failure");
} elsif ($verdicts{$test}) {
$points = $poss;
$passed++;
}
push (@failures, $test) if !$points;
$verdict_counts{$test}++;
push (@rubrics, sprintf ("\t%4s%2d/%2d %s",
$points ? '' : '**', $points, $poss, $test));
$score += $points;
$possible += $poss;
$cnt++;
}
close (RUBRIC);
push (@rubrics, "");
push (@rubrics, "\t- Section summary.");
push (@rubrics, sprintf ("\t%4s%3d/%3d %s",
'', $passed, $cnt, 'tests passed'));
push (@rubrics, sprintf ("\t%4s%3d/%3d %s",
'', $score, $possible, 'points subtotal'));
push (@rubrics, '');
my ($pct) = ($score / $possible) * $max_pct;
push (@summary, sprintf ("%-45s %3d/%3d %5.1f%%/%5.1f%%",
$rubric_suffix,
$score, $possible,
$pct, $max_pct));
$pct_actual += $pct;
$pct_possible += $max_pct;
}
close GRADING;
my ($sum_line)
= "--------------------------------------------- --- --- ------ ------";
unshift (@summary,
"SUMMARY BY TEST SET",
'',
sprintf ("%-45s %3s %3s %6s %6s",
"Test Set", "Pts", "Max", "% Ttl", "% Max"),
$sum_line);
push (@summary,
$sum_line,
sprintf ("%-45s %3s %3s %5.1f%%/%5.1f%%",
'Total', '', '', $pct_actual, $pct_possible));
unshift (@rubrics,
"SUMMARY OF INDIVIDUAL TESTS",
'');
foreach my $name (keys (%verdicts)) {
my ($count) = $verdict_counts{$name};
if (!defined ($count) || $count != 1) {
if (!defined ($count) || !$count) {
push (@overall, "warning: test $name doesn't count for grading");
} else {
push (@overall,
"warning: test $name counted $count times in grading");
}
}
}
push (@overall, sprintf ("TOTAL TESTING SCORE: %.1f%%", $pct_actual));
if (sprintf ("%.1f", $pct_actual) eq sprintf ("%.1f", $pct_possible)) {
push (@overall, "ALL TESTED PASSED -- PERFECT SCORE");
}
my (@divider) = ('', '- ' x 38, '');
print map ("$_\n", @overall, @divider, @summary, @divider, @rubrics);
for my $test (@failures) {
print map ("$_\n", @divider);
print "DETAILS OF $test FAILURE:\n\n";
if (open (RESULT, '<', "$test.result")) {
my $first_line = <RESULT>;
my ($cnt) = 0;
while (<RESULT>) {
print;
$cnt++;
}
close (RESULT);
}
if (open (OUTPUT, '<', "$test.output")) {
print "\nOUTPUT FROM $test:\n\n";
my ($panics, $boots) = (0, 0);
while (<OUTPUT>) {
if (/PANIC/ && ++$panics > 2) {
print "[...details of additional panic(s) omitted...]\n";
last;
}
print;
if (/Pintos booting/ && ++$boots > 1) {
print "[...details of reboot(s) omitted...]\n";
last;
}
}
close (OUTPUT);
}
}
| 10cm | trunk/10cm/pintos/src/tests/make-grade | Perl | oos | 4,096 |
# -*- makefile -*-
include $(patsubst %,$(SRCDIR)/%/Make.tests,$(TEST_SUBDIRS))
PROGS = $(foreach subdir,$(TEST_SUBDIRS),$($(subdir)_PROGS))
TESTS = $(foreach subdir,$(TEST_SUBDIRS),$($(subdir)_TESTS))
EXTRA_GRADES = $(foreach subdir,$(TEST_SUBDIRS),$($(subdir)_EXTRA_GRADES))
OUTPUTS = $(addsuffix .output,$(TESTS) $(EXTRA_GRADES))
ERRORS = $(addsuffix .errors,$(TESTS) $(EXTRA_GRADES))
RESULTS = $(addsuffix .result,$(TESTS) $(EXTRA_GRADES))
ifdef PROGS
include ../../Makefile.userprog
endif
TIMEOUT = 60
clean::
rm -f $(OUTPUTS) $(ERRORS) $(RESULTS)
grade:: results
$(SRCDIR)/tests/make-grade $(SRCDIR) $< $(GRADING_FILE) | tee $@
check:: results
@cat $<
@COUNT="`egrep '^(pass|FAIL) ' $< | wc -l | sed 's/[ ]//g;'`"; \
FAILURES="`egrep '^FAIL ' $< | wc -l | sed 's/[ ]//g;'`"; \
if [ $$FAILURES = 0 ]; then \
echo "All $$COUNT tests passed."; \
else \
echo "$$FAILURES of $$COUNT tests failed."; \
exit 1; \
fi
results: $(RESULTS)
@for d in $(TESTS) $(EXTRA_GRADES); do \
if echo PASS | cmp -s $$d.result -; then \
echo "pass $$d"; \
else \
echo "FAIL $$d"; \
fi; \
done > $@
outputs:: $(OUTPUTS)
$(foreach prog,$(PROGS),$(eval $(prog).output: $(prog)))
$(foreach test,$(TESTS),$(eval $(test).output: $($(test)_PUTFILES)))
$(foreach test,$(TESTS),$(eval $(test).output: TEST = $(test)))
# Prevent an environment variable VERBOSE from surprising us.
VERBOSE =
TESTCMD = pintos -v -k -T $(TIMEOUT)
TESTCMD += $(SIMULATOR)
TESTCMD += $(PINTOSOPTS)
ifeq ($(filter userprog, $(KERNEL_SUBDIRS)), userprog)
TESTCMD += --fs-disk=$(FSDISK)
TESTCMD += $(foreach file,$(PUTFILES),-p $(file) -a $(notdir $(file)))
endif
ifeq ($(filter vm, $(KERNEL_SUBDIRS)), vm)
TESTCMD += --swap-disk=4
endif
TESTCMD += -- -q
TESTCMD += $(KERNELFLAGS)
ifeq ($(filter userprog, $(KERNEL_SUBDIRS)), userprog)
TESTCMD += -f
endif
TESTCMD += $(if $($(TEST)_ARGS),run '$(*F) $($(TEST)_ARGS)',run $(*F))
TESTCMD += < /dev/null
TESTCMD += 2> $(TEST).errors $(if $(VERBOSE),|tee,>) $(TEST).output
%.output: os.dsk
$(TESTCMD)
%.result: %.ck %.output
perl -I$(SRCDIR) $< $* $@
| 10cm | trunk/10cm/pintos/src/tests/Make.tests | Makefile | oos | 2,138 |
use strict;
use warnings;
use tests::random;
sub shuffle {
my ($in, $cnt, $sz) = @_;
$cnt * $sz == length $in or die;
my (@a) = 0...$cnt - 1;
for my $i (0...$cnt - 1) {
my ($j) = $i + random_ulong () % ($cnt - $i);
@a[$i, $j] = @a[$j, $i];
}
my ($out) = "";
$out .= substr ($in, $_ * $sz, $sz) foreach @a;
return $out;
}
1;
| 10cm | trunk/10cm/pintos/src/tests/lib.pm | Perl | oos | 361 |
use strict;
use warnings;
sub arc4_init {
my ($key) = @_;
my (@s) = 0...255;
my ($j) = 0;
for my $i (0...255) {
$j = ($j + $s[$i] + ord (substr ($key, $i % length ($key), 1))) & 0xff;
@s[$i, $j] = @s[$j, $i];
}
return (0, 0, @s);
}
sub arc4_crypt {
my ($arc4, $buf) = @_;
my ($i, $j, @s) = @$arc4;
my ($out) = "";
for my $c (split (//, $buf)) {
$i = ($i + 1) & 0xff;
$j = ($j + $s[$i]) & 0xff;
@s[$i, $j] = @s[$j, $i];
$out .= chr (ord ($c) ^ $s[($s[$i] + $s[$j]) & 0xff]);
}
@$arc4 = ($i, $j, @s);
return $out;
}
1;
| 10cm | trunk/10cm/pintos/src/tests/arc4.pm | Perl | oos | 578 |
use strict;
use warnings;
use tests::Algorithm::Diff;
use File::Temp 'tempfile';
use Fcntl qw(SEEK_SET SEEK_CUR);
sub fail;
sub pass;
die if @ARGV != 2;
our ($test, $src_dir) = @ARGV;
my ($msg_file) = tempfile ();
select ($msg_file);
our (@prereq_tests) = ();
if ($test =~ /^(.*)-persistence$/) {
push (@prereq_tests, $1);
}
for my $prereq_test (@prereq_tests) {
my (@result) = read_text_file ("$prereq_test.result");
fail "Prerequisite test $prereq_test failed.\n" if $result[0] ne 'PASS';
}
# Generic testing.
sub check_expected {
my ($expected) = pop @_;
my (@options) = @_;
my (@output) = read_text_file ("$test.output");
common_checks ("run", @output);
compare_output ("run", @options, \@output, $expected);
}
sub common_checks {
my ($run, @output) = @_;
fail "\u$run produced no output at all\n" if @output == 0;
check_for_panic ($run, @output);
check_for_keyword ($run, "FAIL", @output);
check_for_triple_fault ($run, @output);
check_for_keyword ($run, "TIMEOUT", @output);
fail "\u$run didn't start up properly: no \"Pintos booting\" message\n"
if !grep (/Pintos booting with.*kB RAM\.\.\./, @output);
fail "\u$run didn't start up properly: no \"Boot complete\" message\n"
if !grep (/Boot complete/, @output);
fail "\u$run didn't shut down properly: no \"Timer: # ticks\" message\n"
if !grep (/Timer: \d+ ticks/, @output);
fail "\u$run didn't shut down properly: no \"Powering off\" message\n"
if !grep (/Powering off/, @output);
}
sub check_for_panic {
my ($run, @output) = @_;
my ($panic) = grep (/PANIC/, @output);
return unless defined $panic;
print "Kernel panic in $run: ", substr ($panic, index ($panic, "PANIC")),
"\n";
my (@stack_line) = grep (/Call stack:/, @output);
if (@stack_line != 0) {
my ($addrs) = $stack_line[0] =~ /Call stack:((?: 0x[0-9a-f]+)+)/;
# Find a user program to translate user virtual addresses.
my ($userprog) = "";
$userprog = "$test"
if grep (hex ($_) < 0xc0000000, split (' ', $addrs)) > 0 && -e $test;
# Get and print the backtrace.
my ($trace) = scalar (`backtrace kernel.o $userprog $addrs`);
print "Call stack:$addrs\n";
print "Translation of call stack:\n";
print $trace;
# Print disclaimer.
if ($userprog ne '' && index ($trace, $userprog) >= 0) {
print <<EOF;
Translations of user virtual addresses above are based on a guess at
the binary to use. If this guess is incorrect, then those
translations will be misleading.
EOF
}
}
if ($panic =~ /sec_no \< d-\>capacity/) {
print <<EOF;
\nThis assertion commonly fails when accessing a file via an inode that
has been closed and freed. Freeing an inode clears all its sector
indexes to 0xcccccccc, which is not a valid sector number for disks
smaller than about 1.6 TB.
EOF
}
fail;
}
sub check_for_keyword {
my ($run, $keyword, @output) = @_;
my ($kw_line) = grep (/$keyword/, @output);
return unless defined $kw_line;
# Most output lines are prefixed by (test-name). Eliminate this
# from our message for brevity.
$kw_line =~ s/^\([^\)]+\)\s+//;
print "$run: $kw_line\n";
fail;
}
sub check_for_triple_fault {
my ($run, @output) = @_;
my ($reboots) = grep (/Pintos booting/, @output) - 1;
return unless $reboots > 0;
print <<EOF;
\u$run spontaneously rebooted $reboots times.
This is most often caused by unhandled page faults.
Read the Triple Faults section in the Debugging chapter
of the Pintos manual for more information.
EOF
fail;
}
# Get @output without header or trailer.
sub get_core_output {
my ($run, @output) = @_;
my ($p);
my ($process);
my ($start);
for my $i (0...$#_) {
$start = $i + 1, last
if ($process) = $output[$i] =~ /^Executing '(\S+).*':$/;
}
my ($end);
for my $i ($start...$#output) {
$end = $i - 1, last if $output[$i] =~ /^Execution of '.*' complete.$/;
}
fail "\u$run didn't start a thread or process\n" if !defined $start;
fail "\u$run started '$process' but it never finished\n" if !defined $end;
return @output[$start...$end];
}
sub compare_output {
my ($run) = shift @_;
my ($expected) = pop @_;
my ($output) = pop @_;
my (%options) = @_;
my (@output) = get_core_output ($run, @$output);
fail "\u$run didn't produce any output" if !@output;
my $ignore_exit_codes = exists $options{IGNORE_EXIT_CODES};
if ($ignore_exit_codes) {
delete $options{IGNORE_EXIT_CODES};
@output = grep (!/^[a-zA-Z0-9-_]+: exit\(\-?\d+\)$/, @output);
}
my $ignore_user_faults = exists $options{IGNORE_USER_FAULTS};
if ($ignore_user_faults) {
delete $options{IGNORE_USER_FAULTS};
@output = grep (!/^Page fault at.*in user context\.$/
&& !/: dying due to interrupt 0x0e \(.*\).$/
&& !/^Interrupt 0x0e \(.*\) at eip=/
&& !/^ cr2=.* error=.*/
&& !/^ eax=.* ebx=.* ecx=.* edx=.*/
&& !/^ esi=.* edi=.* esp=.* ebp=.*/
&& !/^ cs=.* ds=.* es=.* ss=.*/, @output);
}
die "unknown option " . (keys (%options))[0] . "\n" if %options;
my ($msg);
# Compare actual output against each allowed output.
if (ref ($expected) eq 'ARRAY') {
my ($i) = 0;
$expected = {map ((++$i => $_), @$expected)};
}
foreach my $key (keys %$expected) {
my (@expected) = split ("\n", $expected->{$key});
$msg .= "Acceptable output:\n";
$msg .= join ('', map (" $_\n", @expected));
# Check whether actual and expected match.
# If it's a perfect match, we're done.
if ($#output == $#expected) {
my ($eq) = 1;
for (my ($i) = 0; $i <= $#expected; $i++) {
$eq = 0 if $output[$i] ne $expected[$i];
}
return $key if $eq;
}
# They differ. Output a diff.
my (@diff) = "";
my ($d) = Algorithm::Diff->new (\@expected, \@output);
while ($d->Next ()) {
my ($ef, $el, $af, $al) = $d->Get (qw (min1 max1 min2 max2));
if ($d->Same ()) {
push (@diff, map (" $_\n", $d->Items (1)));
} else {
push (@diff, map ("- $_\n", $d->Items (1))) if $d->Items (1);
push (@diff, map ("+ $_\n", $d->Items (2))) if $d->Items (2);
}
}
$msg .= "Differences in `diff -u' format:\n";
$msg .= join ('', @diff);
}
# Failed to match. Report failure.
$msg .= "\n(Process exit codes are excluded for matching purposes.)\n"
if $ignore_exit_codes;
$msg .= "\n(User fault messages are excluded for matching purposes.)\n"
if $ignore_user_faults;
fail "Test output failed to match any acceptable form.\n\n$msg";
}
# File system extraction.
# check_archive (\%CONTENTS)
#
# Checks that the extracted file system's contents match \%CONTENTS.
# Each key in the hash is a file name. Each value may be:
#
# - $FILE: Name of a host file containing the expected contents.
#
# - [$FILE, $OFFSET, $LENGTH]: An excerpt of host file $FILE
# comprising the $LENGTH bytes starting at $OFFSET.
#
# - [$CONTENTS]: The literal expected file contents, as a string.
#
# - {SUBDIR}: A subdirectory, in the same form described here,
# recursively.
sub check_archive {
my ($expected_hier) = @_;
my (@output) = read_text_file ("$test.output");
common_checks ("file system extraction run", @output);
@output = get_core_output ("file system extraction run", @output);
@output = grep (!/^[a-zA-Z0-9-_]+: exit\(\d+\)$/, @output);
fail join ("\n", "Error extracting file system:", @output) if @output;
my ($test_base_name) = $test;
$test_base_name =~ s%.*/%%;
$test_base_name =~ s%-persistence$%%;
$expected_hier->{$test_base_name} = $prereq_tests[0];
$expected_hier->{'tar'} = 'tests/filesys/extended/tar';
my (%expected) = normalize_fs (flatten_hierarchy ($expected_hier, ""));
my (%actual) = read_tar ("$prereq_tests[0].tar");
my ($errors) = 0;
foreach my $name (sort keys %expected) {
if (exists $actual{$name}) {
if (is_dir ($actual{$name}) && !is_dir ($expected{$name})) {
print "$name is a directory but should be an ordinary file.\n";
$errors++;
} elsif (!is_dir ($actual{$name}) && is_dir ($expected{$name})) {
print "$name is an ordinary file but should be a directory.\n";
$errors++;
}
} else {
print "$name is missing from the file system.\n";
$errors++;
}
}
foreach my $name (sort keys %actual) {
if (!exists $expected{$name}) {
if ($name =~ /^[[:print:]]+$/) {
print "$name exists in the file system but it should not.\n";
} else {
my ($esc_name) = $name;
$esc_name =~ s/[^[:print:]]/./g;
print <<EOF;
$esc_name exists in the file system but should not. (The name
of this file contains unusual characters that were printed as `.'.)
EOF
}
$errors++;
}
}
if ($errors) {
print "\nActual contents of file system:\n";
print_fs (%actual);
print "\nExpected contents of file system:\n";
print_fs (%expected);
} else {
foreach my $name (sort keys %expected) {
if (!is_dir ($expected{$name})) {
my ($exp_file, $exp_length) = open_file ($expected{$name});
my ($act_file, $act_length) = open_file ($actual{$name});
$errors += !compare_files ($exp_file, $exp_length,
$act_file, $act_length, $name,
!$errors);
close ($exp_file);
close ($act_file);
}
}
}
fail "Extracted file system contents are not correct.\n" if $errors;
}
# open_file ([$FILE, $OFFSET, $LENGTH])
# open_file ([$CONTENTS])
#
# Opens a file for the contents passed in, which must be in one of
# the two above forms that correspond to check_archive() arguments.
#
# Returns ($HANDLE, $LENGTH), where $HANDLE is the file's handle and
# $LENGTH is the number of bytes in the file's content.
sub open_file {
my ($value) = @_;
die if ref ($value) ne 'ARRAY';
my ($file) = tempfile ();
my ($length);
if (@$value == 1) {
$length = length ($value->[0]);
$file = tempfile ();
syswrite ($file, $value->[0]) == $length
or die "writing temporary file: $!\n";
sysseek ($file, 0, SEEK_SET);
} elsif (@$value == 3) {
$length = $value->[2];
open ($file, '<', $value->[0]) or die "$value->[0]: open: $!\n";
die "$value->[0]: file is smaller than expected\n"
if -s $file < $value->[1] + $length;
sysseek ($file, $value->[1], SEEK_SET);
} else {
die;
}
return ($file, $length);
}
# compare_files ($A, $A_SIZE, $B, $B_SIZE, $NAME, $VERBOSE)
#
# Compares $A_SIZE bytes in $A to $B_SIZE bytes in $B.
# ($A and $B are handles.)
# If their contents differ, prints a brief message describing
# the differences, using $NAME to identify the file.
# The message contains more detail if $VERBOSE is nonzero.
# Returns 1 if the contents are identical, 0 otherwise.
sub compare_files {
my ($a, $a_size, $b, $b_size, $name, $verbose) = @_;
my ($ofs) = 0;
select(STDOUT);
for (;;) {
my ($a_amt) = $a_size >= 1024 ? 1024 : $a_size;
my ($b_amt) = $b_size >= 1024 ? 1024 : $b_size;
my ($a_data, $b_data);
if (!defined (sysread ($a, $a_data, $a_amt))
|| !defined (sysread ($b, $b_data, $b_amt))) {
die "reading $name: $!\n";
}
my ($a_len) = length $a_data;
my ($b_len) = length $b_data;
last if $a_len == 0 && $b_len == 0;
if ($a_data ne $b_data) {
my ($min_len) = $a_len < $b_len ? $a_len : $b_len;
my ($diff_ofs);
for ($diff_ofs = 0; $diff_ofs < $min_len; $diff_ofs++) {
last if (substr ($a_data, $diff_ofs, 1)
ne substr ($b_data, $diff_ofs, 1));
}
printf "\nFile $name differs from expected "
. "starting at offset 0x%x.\n", $ofs + $diff_ofs;
if ($verbose ) {
print "Expected contents:\n";
hex_dump (substr ($a_data, $diff_ofs, 64), $ofs + $diff_ofs);
print "Actual contents:\n";
hex_dump (substr ($b_data, $diff_ofs, 64), $ofs + $diff_ofs);
}
return 0;
}
$ofs += $a_len;
$a_size -= $a_len;
$b_size -= $b_len;
}
return 1;
}
# hex_dump ($DATA, $OFS)
#
# Prints $DATA in hex and text formats.
# The first byte of $DATA corresponds to logical offset $OFS
# in whatever file the data comes from.
sub hex_dump {
my ($data, $ofs) = @_;
if ($data eq '') {
printf " (File ends at offset %08x.)\n", $ofs;
return;
}
my ($per_line) = 16;
while ((my $size = length ($data)) > 0) {
my ($start) = $ofs % $per_line;
my ($end) = $per_line;
$end = $start + $size if $end - $start > $size;
my ($n) = $end - $start;
printf "0x%08x ", int ($ofs / $per_line) * $per_line;
# Hex version.
print " " x $start;
for my $i ($start...$end - 1) {
printf "%02x", ord (substr ($data, $i - $start, 1));
print $i == $per_line / 2 - 1 ? '-' : ' ';
}
print " " x ($per_line - $end);
# Character version.
my ($esc_data) = substr ($data, 0, $n);
$esc_data =~ s/[^[:print:]]/./g;
print "|", " " x $start, $esc_data, " " x ($per_line - $end), "|";
print "\n";
$data = substr ($data, $n);
$ofs += $n;
}
}
# print_fs (%FS)
#
# Prints a list of files in %FS, which must be a file system
# as flattened by flatten_hierarchy() and normalized by
# normalize_fs().
sub print_fs {
my (%fs) = @_;
foreach my $name (sort keys %fs) {
my ($esc_name) = $name;
$esc_name =~ s/[^[:print:]]/./g;
print "$esc_name: ";
if (!is_dir ($fs{$name})) {
print +file_size ($fs{$name}), "-byte file";
} else {
print "directory";
}
print "\n";
}
print "(empty)\n" if !@_;
}
# normalize_fs (%FS)
#
# Takes a file system as flattened by flatten_hierarchy().
# Returns a similar file system in which values of the form $FILE
# are replaced by those of the form [$FILE, $OFFSET, $LENGTH].
sub normalize_fs {
my (%fs) = @_;
foreach my $name (keys %fs) {
my ($value) = $fs{$name};
next if is_dir ($value) || ref ($value) ne '';
die "can't open $value\n" if !stat $value;
$fs{$name} = [$value, 0, -s _];
}
return %fs;
}
# is_dir ($VALUE)
#
# Takes a value like one in the hash returned by flatten_hierarchy()
# and returns 1 if it represents a directory, 0 otherwise.
sub is_dir {
my ($value) = @_;
return ref ($value) eq '' && $value eq 'directory';
}
# file_size ($VALUE)
#
# Takes a value like one in the hash returned by flatten_hierarchy()
# and returns the size of the file it represents.
sub file_size {
my ($value) = @_;
die if is_dir ($value);
die if ref ($value) ne 'ARRAY';
return @$value > 1 ? $value->[2] : length ($value->[0]);
}
# flatten_hierarchy ($HIER_FS, $PREFIX)
#
# Takes a file system in the format expected by check_archive() and
# returns a "flattened" version in which file names include all parent
# directory names and the value of directories is just "directory".
sub flatten_hierarchy {
my (%hier_fs) = %{$_[0]};
my ($prefix) = $_[1];
my (%flat_fs);
for my $name (keys %hier_fs) {
my ($value) = $hier_fs{$name};
if (ref $value eq 'HASH') {
%flat_fs = (%flat_fs, flatten_hierarchy ($value, "$prefix$name/"));
$flat_fs{"$prefix$name"} = 'directory';
} else {
$flat_fs{"$prefix$name"} = $value;
}
}
return %flat_fs;
}
# read_tar ($ARCHIVE)
#
# Reads the ustar-format tar file in $ARCHIVE
# and returns a flattened file system for it.
sub read_tar {
my ($archive) = @_;
my (%content);
open (ARCHIVE, '<', $archive) or fail "$archive: open: $!\n";
for (;;) {
my ($header);
if ((my $retval = sysread (ARCHIVE, $header, 512)) != 512) {
fail "$archive: unexpected end of file\n" if $retval >= 0;
fail "$archive: read: $!\n";
}
last if $header eq "\0" x 512;
# Verify magic numbers.
if (substr ($header, 257, 6) ne "ustar\0"
|| substr ($header, 263, 2) ne '00') {
fail "$archive: corrupt ustar header\n";
}
# Verify checksum.
my ($chksum) = oct (unpack ("Z*", substr ($header, 148, 8, ' ' x 8)));
my ($correct_chksum) = unpack ("%32a*", $header);
fail "$archive: bad header checksum\n" if $chksum != $correct_chksum;
# Get file name.
my ($name) = unpack ("Z100", $header);
my ($prefix) = unpack ("Z*", substr ($header, 345));
$name = "$prefix/$name" if $prefix ne '';
fail "$archive: contains file with empty name" if $name eq '';
# Get type.
my ($typeflag) = substr ($header, 156, 1);
$typeflag = '0' if $typeflag eq "\0";
fail "unknown file type '$typeflag'\n" if $typeflag !~ /[05]/;
# Get size.
my ($size) = oct (unpack ("Z*", substr ($header, 124, 12)));
fail "bad size $size\n" if $size < 0;
$size = 0 if $typeflag eq '5';
# Store content.
$name =~ s%^(/|\./|\.\./)*%%; # Strip leading "/", "./", "../".
$name = '' if $name eq '.' || $name eq '..';
if (exists $content{$name}) {
fail "$archive: contains multiple entries for $name\n";
}
if ($typeflag eq '5') {
$content{$name} = 'directory' if $name ne '';
} else {
fail "$archive: contains file with empty name\n" if $name eq '';
my ($position) = sysseek (ARCHIVE, 0, SEEK_CUR);
$content{$name} = [$archive, $position, $size];
sysseek (ARCHIVE, int (($size + 511) / 512) * 512, SEEK_CUR);
}
}
close (ARCHIVE);
return %content;
}
# Utilities.
sub fail {
finish ("FAIL", @_);
}
sub pass {
finish ("PASS", @_);
}
sub finish {
my ($verdict, @messages) = @_;
seek ($msg_file, 0, 0);
push (@messages, <$msg_file>);
close ($msg_file);
chomp (@messages);
my ($result_fn) = "$test.result";
open (RESULT, '>', $result_fn) or die "$result_fn: create: $!\n";
print RESULT "$verdict\n";
print RESULT "$_\n" foreach @messages;
close (RESULT);
if ($verdict eq 'PASS') {
print STDOUT "pass $test\n";
} else {
print STDOUT "FAIL $test\n";
}
print STDOUT "$_\n" foreach @messages;
exit 0;
}
sub read_text_file {
my ($file_name) = @_;
open (FILE, '<', $file_name) or die "$file_name: open: $!\n";
my (@content) = <FILE>;
chomp (@content);
close (FILE);
return @content;
}
1;
| 10cm | trunk/10cm/pintos/src/tests/tests.pm | Perl | oos | 17,803 |
#include <stdint.h>
#include "tests/arc4.h"
/* Swap bytes. */
static inline void
swap_byte (uint8_t *a, uint8_t *b)
{
uint8_t t = *a;
*a = *b;
*b = t;
}
void
arc4_init (struct arc4 *arc4, const void *key_, size_t size)
{
const uint8_t *key = key_;
size_t key_idx;
uint8_t *s;
int i, j;
s = arc4->s;
arc4->i = arc4->j = 0;
for (i = 0; i < 256; i++)
s[i] = i;
for (key_idx = 0, i = j = 0; i < 256; i++)
{
j = (j + s[i] + key[key_idx]) & 255;
swap_byte (s + i, s + j);
if (++key_idx >= size)
key_idx = 0;
}
}
void
arc4_crypt (struct arc4 *arc4, void *buf_, size_t size)
{
uint8_t *buf = buf_;
uint8_t *s;
uint8_t i, j;
s = arc4->s;
i = arc4->i;
j = arc4->j;
while (size-- > 0)
{
i += 1;
j += s[i];
swap_byte (s + i, s + j);
*buf++ ^= s[(s[i] + s[j]) & 255];
}
arc4->i = i;
arc4->j = j;
}
| 10cm | trunk/10cm/pintos/src/tests/arc4.c | C | oos | 900 |
# From the `cksum' entry in SUSv3.
use strict;
use warnings;
my (@crctab) =
(0x00000000,
0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b,
0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6,
0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac,
0x5bd4b01b, 0x569796c2, 0x52568b75, 0x6a1936c8, 0x6ed82b7f,
0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a,
0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,
0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58,
0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033,
0xa4ad16ea, 0xa06c0b5d, 0xd4326d90, 0xd0f37027, 0xddb056fe,
0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4,
0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0,
0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5,
0x2ac12072, 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16,
0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, 0x7897ab07,
0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c,
0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1,
0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b,
0xbb60adfc, 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698,
0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d,
0x94ea7b2a, 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e,
0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, 0xc6bcf05f,
0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34,
0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80,
0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a,
0x58c1663d, 0x558240e4, 0x51435d53, 0x251d3b9e, 0x21dc2629,
0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c,
0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,
0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e,
0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65,
0xeba91bbc, 0xef68060b, 0xd727bbb6, 0xd3e6a601, 0xdea580d8,
0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2,
0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71,
0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74,
0x857130c3, 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640,
0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, 0x7b827d21,
0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a,
0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, 0x18197087,
0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d,
0x2056cd3a, 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce,
0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb,
0xdbee767c, 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18,
0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, 0x89b8fd09,
0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662,
0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf,
0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4);
sub cksum {
my ($b) = @_;
my ($n) = length ($b);
my ($s) = 0;
for my $i (0...$n - 1) {
my ($c) = ord (substr ($b, $i, 1));
$s = ($s << 8) ^ $crctab[($s >> 24) ^ $c];
$s &= 0xffff_ffff;
}
while ($n != 0) {
my ($c) = $n & 0xff;
$n >>= 8;
$s = ($s << 8) ^ $crctab[($s >> 24) ^ $c];
$s &= 0xffff_ffff;
}
return ~$s & 0xffff_ffff;
}
sub cksum_file {
my ($file) = @_;
open (FILE, '<', $file) or die "$file: open: $!\n";
my ($data);
sysread (FILE, $data, -s FILE) == -s FILE or die "$file: read: $!\n";
close (FILE);
return cksum ($data);
}
1;
| 10cm | trunk/10cm/pintos/src/tests/cksum.pm | Perl | oos | 3,910 |
#include "tests/lib.h"
#include <random.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <syscall.h>
const char *test_name;
bool quiet = false;
static void
vmsg (const char *format, va_list args, const char *suffix)
{
/* We go to some trouble to stuff the entire message into a
single buffer and output it in a single system call, because
that'll (typically) ensure that it gets sent to the console
atomically. Otherwise kernel messages like "foo: exit(0)"
can end up being interleaved if we're unlucky. */
static char buf[1024];
snprintf (buf, sizeof buf, "(%s) ", test_name);
vsnprintf (buf + strlen (buf), sizeof buf - strlen (buf), format, args);
strlcpy (buf + strlen (buf), suffix, sizeof buf - strlen (buf));
write (STDOUT_FILENO, buf, strlen (buf));
}
void
msg (const char *format, ...)
{
va_list args;
if (quiet)
return;
va_start (args, format);
vmsg (format, args, "\n");
va_end (args);
}
void
fail (const char *format, ...)
{
va_list args;
va_start (args, format);
vmsg (format, args, ": FAILED\n");
va_end (args);
exit (1);
}
static void
swap (void *a_, void *b_, size_t size)
{
uint8_t *a = a_;
uint8_t *b = b_;
size_t i;
for (i = 0; i < size; i++)
{
uint8_t t = a[i];
a[i] = b[i];
b[i] = t;
}
}
void
shuffle (void *buf_, size_t cnt, size_t size)
{
char *buf = buf_;
size_t i;
for (i = 0; i < cnt; i++)
{
size_t j = i + random_ulong () % (cnt - i);
swap (buf + i * size, buf + j * size, size);
}
}
void
exec_children (const char *child_name, pid_t pids[], size_t child_cnt)
{
size_t i;
for (i = 0; i < child_cnt; i++)
{
char cmd_line[128];
snprintf (cmd_line, sizeof cmd_line, "%s %zu", child_name, i);
CHECK ((pids[i] = exec (cmd_line)) != PID_ERROR,
"exec child %zu of %zu: \"%s\"", i + 1, child_cnt, cmd_line);
}
}
void
wait_children (pid_t pids[], size_t child_cnt)
{
size_t i;
for (i = 0; i < child_cnt; i++)
{
int status = wait (pids[i]);
CHECK (status == (int) i,
"wait for child %zu of %zu returned %d (expected %zu)",
i + 1, child_cnt, status, i);
}
}
void
check_file_handle (int fd,
const char *file_name, const void *buf_, size_t size)
{
const char *buf = buf_;
size_t ofs = 0;
size_t file_size;
/* Warn about file of wrong size. Don't fail yet because we
may still be able to get more information by reading the
file. */
file_size = filesize (fd);
if (file_size != size)
msg ("size of %s (%zu) differs from expected (%zu)",
file_name, file_size, size);
/* Read the file block-by-block, comparing data as we go. */
while (ofs < size)
{
char block[512];
size_t block_size, ret_val;
block_size = size - ofs;
if (block_size > sizeof block)
block_size = sizeof block;
ret_val = read (fd, block, block_size);
if (ret_val != block_size)
fail ("read of %zu bytes at offset %zu in \"%s\" returned %zu",
block_size, ofs, file_name, ret_val);
compare_bytes (block, buf + ofs, block_size, ofs, file_name);
ofs += block_size;
}
/* Now fail due to wrong file size. */
if (file_size != size)
fail ("size of %s (%zu) differs from expected (%zu)",
file_name, file_size, size);
msg ("verified contents of \"%s\"", file_name);
}
void
check_file (const char *file_name, const void *buf, size_t size)
{
int fd;
CHECK ((fd = open (file_name)) > 1, "open \"%s\" for verification",
file_name);
check_file_handle (fd, file_name, buf, size);
msg ("close \"%s\"", file_name);
close (fd);
}
void
compare_bytes (const void *read_data_, const void *expected_data_, size_t size,
size_t ofs, const char *file_name)
{
const uint8_t *read_data = read_data_;
const uint8_t *expected_data = expected_data_;
size_t i, j;
size_t show_cnt;
if (!memcmp (read_data, expected_data, size))
return;
for (i = 0; i < size; i++)
if (read_data[i] != expected_data[i])
break;
for (j = i + 1; j < size; j++)
if (read_data[j] == expected_data[j])
break;
quiet = false;
msg ("%zu bytes read starting at offset %zu in \"%s\" differ "
"from expected.", j - i, ofs + i, file_name);
show_cnt = j - i;
if (j - i > 64)
{
show_cnt = 64;
msg ("Showing first differing %zu bytes.", show_cnt);
}
msg ("Data actually read:");
hex_dump (ofs + i, read_data + i, show_cnt, true);
msg ("Expected data:");
hex_dump (ofs + i, expected_data + i, show_cnt, true);
fail ("%zu bytes read starting at offset %zu in \"%s\" differ "
"from expected", j - i, ofs + i, file_name);
}
| 10cm | trunk/10cm/pintos/src/tests/lib.c | C | oos | 4,800 |
/* crctab[] and cksum() are from the `cksum' entry in SUSv3. */
#include <stdint.h>
#include "tests/cksum.h"
static unsigned long crctab[] = {
0x00000000,
0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b,
0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6,
0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac,
0x5bd4b01b, 0x569796c2, 0x52568b75, 0x6a1936c8, 0x6ed82b7f,
0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a,
0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,
0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58,
0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033,
0xa4ad16ea, 0xa06c0b5d, 0xd4326d90, 0xd0f37027, 0xddb056fe,
0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4,
0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0,
0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5,
0x2ac12072, 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16,
0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, 0x7897ab07,
0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c,
0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1,
0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b,
0xbb60adfc, 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698,
0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d,
0x94ea7b2a, 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e,
0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, 0xc6bcf05f,
0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34,
0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80,
0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a,
0x58c1663d, 0x558240e4, 0x51435d53, 0x251d3b9e, 0x21dc2629,
0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c,
0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,
0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e,
0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65,
0xeba91bbc, 0xef68060b, 0xd727bbb6, 0xd3e6a601, 0xdea580d8,
0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2,
0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71,
0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74,
0x857130c3, 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640,
0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, 0x7b827d21,
0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a,
0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, 0x18197087,
0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d,
0x2056cd3a, 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce,
0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb,
0xdbee767c, 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18,
0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, 0x89b8fd09,
0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662,
0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf,
0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
};
/* This is the algorithm used by the Posix `cksum' utility. */
unsigned long
cksum (const void *b_, size_t n)
{
const unsigned char *b = b_;
uint32_t s = 0;
size_t i;
for (i = n; i > 0; --i)
{
unsigned char c = *b++;
s = (s << 8) ^ crctab[(s >> 24) ^ c];
}
while (n != 0)
{
unsigned char c = n;
n >>= 8;
s = (s << 8) ^ crctab[(s >> 24) ^ c];
}
return ~s;
}
#ifdef STANDALONE_TEST
#include <stdio.h>
int
main (void)
{
char buf[65536];
int n = fread (buf, 1, sizeof buf, stdin);
printf ("%lu\n", cksum (buf, n));
return 0;
}
#endif
| 10cm | trunk/10cm/pintos/src/tests/cksum.c | C | oos | 3,922 |
# -*- makefile -*-
SHELL = /bin/sh
VPATH = $(SRCDIR)
# Binary utilities.
# If the host appears to be x86, use the normal tools.
# If it's x86-64, use the compiler and linker in 32-bit mode.
# Otherwise assume cross-tools are installed as i386-elf-*.
X86 = i.86\|pentium.*\|[pk][56]\|nexgen\|viac3\|6x86\|athlon.*\|i86pc
X86_64 = x86_64
ifneq (0, $(shell expr `uname -m` : '$(X86)'))
CC = gcc
LD = ld
OBJCOPY = objcopy
else
ifneq (0, $(shell expr `uname -m` : '$(X86_64)'))
CC = gcc -m32
LD = ld -melf_i386
OBJCOPY = objcopy
else
CC = i386-elf-gcc
LD = i386-elf-ld
OBJCOPY = i386-elf-objcopy
endif
endif
ifeq ($(strip $(shell command -v $(CC) 2> /dev/null)),)
$(warning *** Compiler ($(CC)) not found. Did you set $$PATH properly? Please refer to the Getting Started section in the documentation for details. ***)
endif
# Compiler and assembler invocation.
DEFINES =
WARNINGS = -Wall -W -Wstrict-prototypes -Wmissing-prototypes -Wsystem-headers
CFLAGS = -g -msoft-float -O
CPPFLAGS = -nostdinc -I$(SRCDIR) -I$(SRCDIR)/lib
ASFLAGS = -Wa,--gstabs
LDFLAGS =
DEPS = -MMD -MF $(@:.o=.d)
# Turn off -fstack-protector, which we don't support.
ifeq ($(strip $(shell echo | $(CC) -fno-stack-protector -E - > /dev/null 2>&1; echo $$?)),0)
CFLAGS += -fno-stack-protector
endif
# Turn off --build-id in the linker, which confuses the Pintos loader.
ifeq ($(strip $(shell $(LD) --build-id=none -e 0 /dev/null -o /dev/null 2>&1; echo $$?)),0)
LDFLAGS += -Wl,--build-id=none
endif
%.o: %.c
$(CC) -c $< -o $@ $(CFLAGS) $(CPPFLAGS) $(WARNINGS) $(DEFINES) $(DEPS)
%.o: %.S
$(CC) -c $< -o $@ $(ASFLAGS) $(CPPFLAGS) $(DEFINES) $(DEPS)
| 10cm | trunk/10cm/pintos/src/Make.config | Makefile | oos | 1,664 |
#! /bin/sh -e
if test -z "$SRCDIR" || test -z "$PINTOSDIR" || test -z "$DSTDIR"; then
echo "usage: env SRCDIR=<srcdir> PINTOSDIR=<srcdir> DSTDIR=<dstdir> sh $0"
echo " where <srcdir> contains bochs-2.2.6.tar.gz"
echo " and <pintosdir> is the root of the pintos source tree"
echo " and <dstdir> is the installation prefix (e.g. /usr/local)"
exit 1
fi
cd /tmp
mkdir $$
cd $$
mkdir bochs-2.2.6
tar xzf $SRCDIR/bochs-2.2.6.tar.gz
cd bochs-2.2.6
cat $PINTOSDIR/src/misc/bochs-2.2.6-ms-extensions.patch | patch -p1
cat $PINTOSDIR/src/misc/bochs-2.2.6-big-endian.patch | patch -p1
cat $PINTOSDIR/src/misc/bochs-2.2.6-jitter.patch | patch -p1
cat $PINTOSDIR/src/misc/bochs-2.2.6-triple-fault.patch | patch -p1
cat $PINTOSDIR/src/misc/bochs-2.2.6-solaris-tty.patch | patch -p1
cat $PINTOSDIR/src/misc/bochs-2.2.6-page-fault-segv.patch | patch -p1
cat $PINTOSDIR/src/misc/bochs-2.2.6-paranoia.patch | patch -p1
cat $PINTOSDIR/src/misc/bochs-2.2.6-gdbstub-ENN.patch | patch -p1
if test "`uname -s`" = "SunOS"; then
cat $PINTOSDIR/src/misc/bochs-2.2.6-solaris-link.patch | patch -p1
fi
CFGOPTS="--with-x --with-x11 --with-term --with-nogui --prefix=$DSTDIR"
mkdir plain &&
cd plain &&
../configure $CFGOPTS --enable-gdb-stub &&
make &&
make install &&
cd ..
mkdir with-dbg &&
cd with-dbg &&
../configure --enable-debugger $CFGOPTS &&
make &&
cp bochs $DSTDIR/bin/bochs-dbg &&
cd ..
| 10cm | trunk/10cm/pintos/src/misc/bochs-2.2.6-build.sh | Shell | oos | 1,486 |
#! /bin/sh -e
if test -z "$SRCDIR" || test -z "$PINTOSDIR" || test -z "$DSTDIR"; then
echo "usage: env SRCDIR=<srcdir> PINTOSDIR=<srcdir> DSTDIR=<dstdir> sh $0"
echo " where <srcdir> contains bochs-2.2.6.tar.gz"
echo " and <pintosdir> is the root of the pintos source tree"
echo " and <dstdir> is the installation prefix (e.g. /usr/local)"
exit 1
fi
cd /tmp
mkdir $$
cd $$
mkdir bochs-2.2.6
tar xzf $SRCDIR/bochs-2.2.6.tar.gz
cd bochs-2.2.6
cat $PINTOSDIR/src/misc/bochs-2.2.6-ms-extensions.patch | patch -p1
cat $PINTOSDIR/src/misc/bochs-2.2.6-big-endian.patch | patch -p1
cat $PINTOSDIR/src/misc/bochs-2.2.6-jitter.patch | patch -p1
cat $PINTOSDIR/src/misc/bochs-2.2.6-triple-fault.patch | patch -p1
cat $PINTOSDIR/src/misc/bochs-2.2.6-solaris-tty.patch | patch -p1
cat $PINTOSDIR/src/misc/bochs-2.2.6-page-fault-segv.patch | patch -p1
cat $PINTOSDIR/src/misc/bochs-2.2.6-paranoia.patch | patch -p1
cat $PINTOSDIR/src/misc/bochs-2.2.6-gdbstub-ENN.patch | patch -p1
if test "`uname -s`" = "SunOS"; then
cat $PINTOSDIR/src/misc/bochs-2.2.6-solaris-link.patch | patch -p1
fi
CFGOPTS="--with-x --with-x11 --with-term --with-nogui --prefix=$DSTDIR"
mkdir plain &&
cd plain &&
../configure $CFGOPTS --enable-gdb-stub &&
make &&
make install &&
cd ..
mkdir with-dbg &&
cd with-dbg &&
../configure --enable-debugger $CFGOPTS &&
make &&
cp bochs $DSTDIR/bin/bochs-dbg &&
cd ..
| 10cm | trunk/10cm/pintos/src/misc/.svn/text-base/bochs-2.2.6-build.sh.svn-base | Shell | oos | 1,486 |
BUILD_SUBDIRS = threads userprog vm filesys
all::
@echo "Run 'make' in subdirectories: $(BUILD_SUBDIRS)."
@echo "This top-level make has only 'clean' targets."
CLEAN_SUBDIRS = $(BUILD_SUBDIRS) examples utils
clean::
for d in $(CLEAN_SUBDIRS); do $(MAKE) -C $$d $@; done
rm -f TAGS tags
distclean:: clean
find . -name '*~' -exec rm '{}' \;
TAGS_SUBDIRS = $(BUILD_SUBDIRS) devices lib
TAGS_SOURCES = find $(TAGS_SUBDIRS) -name \*.[chS] -print
TAGS::
etags --members `$(TAGS_SOURCES)`
tags::
ctags -T --no-warn `$(TAGS_SOURCES)`
cscope.files::
$(TAGS_SOURCES) > cscope.files
cscope:: cscope.files
cscope -b -q -k
| 10cm | trunk/10cm/pintos/src/Makefile | Makefile | oos | 628 |
#include <ustar.h>
#include <limits.h>
#include <packed.h>
#include <stdio.h>
#include <string.h>
/* Header for ustar-format tar archive. See the documentation of
the "pax" utility in [SUSv3] for the the "ustar" format
specification. */
struct ustar_header
{
char name[100]; /* File name. Null-terminated if room. */
char mode[8]; /* Permissions as octal string. */
char uid[8]; /* User ID as octal string. */
char gid[8]; /* Group ID as octal string. */
char size[12]; /* File size in bytes as octal string. */
char mtime[12]; /* Modification time in seconds
from Jan 1, 1970, as octal string. */
char chksum[8]; /* Sum of octets in header as octal string. */
char typeflag; /* An enum ustar_type value. */
char linkname[100]; /* Name of link target.
Null-terminated if room. */
char magic[6]; /* "ustar\0" */
char version[2]; /* "00" */
char uname[32]; /* User name, always null-terminated. */
char gname[32]; /* Group name, always null-terminated. */
char devmajor[8]; /* Device major number as octal string. */
char devminor[8]; /* Device minor number as octal string. */
char prefix[155]; /* Prefix to file name.
Null-terminated if room. */
char padding[12]; /* Pad to 512 bytes. */
}
PACKED;
/* Returns the checksum for the given ustar format HEADER. */
static unsigned int
calculate_chksum (const struct ustar_header *h)
{
const uint8_t *header = (const uint8_t *) h;
unsigned int chksum;
size_t i;
chksum = 0;
for (i = 0; i < USTAR_HEADER_SIZE; i++)
{
/* The ustar checksum is calculated as if the chksum field
were all spaces. */
const size_t chksum_start = offsetof (struct ustar_header, chksum);
const size_t chksum_end = chksum_start + sizeof h->chksum;
bool in_chksum_field = i >= chksum_start && i < chksum_end;
chksum += in_chksum_field ? ' ' : header[i];
}
return chksum;
}
/* Drop possibly dangerous prefixes from FILE_NAME and return the
stripped name. An archive with file names that start with "/"
or "../" could cause a naive tar extractor to write to
arbitrary parts of the file system, not just the destination
directory. We don't want to create such archives or be such a
naive extractor.
The return value can be a suffix of FILE_NAME or a string
literal. */
static const char *
strip_antisocial_prefixes (const char *file_name)
{
while (*file_name == '/'
|| !memcmp (file_name, "./", 2)
|| !memcmp (file_name, "../", 3))
file_name = strchr (file_name, '/') + 1;
return *file_name == '\0' || !strcmp (file_name, "..") ? "." : file_name;
}
/* Composes HEADER as a USTAR_HEADER_SIZE (512)-byte archive
header in ustar format for a SIZE-byte file named FILE_NAME of
the given TYPE. The caller is responsible for writing the
header to a file or device.
If successful, returns true. On failure (due to an
excessively long file name), returns false. */
bool
ustar_make_header (const char *file_name, enum ustar_type type,
int size, char header[USTAR_HEADER_SIZE])
{
struct ustar_header *h = (struct ustar_header *) header;
ASSERT (sizeof (struct ustar_header) == USTAR_HEADER_SIZE);
ASSERT (type == USTAR_REGULAR || type == USTAR_DIRECTORY);
/* Check file name. */
file_name = strip_antisocial_prefixes (file_name);
if (strlen (file_name) > 99)
{
printf ("%s: file name too long\n", file_name);
return false;
}
/* Fill in header except for final checksum. */
memset (h, 0, sizeof *h);
strlcpy (h->name, file_name, sizeof h->name);
snprintf (h->mode, sizeof h->mode, "%07o",
type == USTAR_REGULAR ? 0644 : 0755);
strlcpy (h->uid, "0000000", sizeof h->uid);
strlcpy (h->gid, "0000000", sizeof h->gid);
snprintf (h->size, sizeof h->size, "%011o", size);
snprintf (h->mtime, sizeof h->size, "%011o", 1136102400);
h->typeflag = type;
strlcpy (h->magic, "ustar", sizeof h->magic);
h->version[0] = h->version[1] = '0';
strlcpy (h->gname, "root", sizeof h->gname);
strlcpy (h->uname, "root", sizeof h->uname);
/* Compute and fill in final checksum. */
snprintf (h->chksum, sizeof h->chksum, "%07o", calculate_chksum (h));
return true;
}
/* Parses a SIZE-byte octal field in S in the format used by
ustar format. If successful, stores the field's value in
*VALUE and returns true; on failure, returns false.
ustar octal fields consist of a sequence of octal digits
terminated by a space or a null byte. The ustar specification
seems ambiguous as to whether these fields must be padded on
the left with '0's, so we accept any field that fits in the
available space, regardless of whether it fills the space. */
static bool
parse_octal_field (const char *s, size_t size, unsigned long int *value)
{
size_t ofs;
*value = 0;
for (ofs = 0; ofs < size; ofs++)
{
char c = s[ofs];
if (c >= '0' && c <= '7')
{
if (*value > ULONG_MAX / 8)
{
/* Overflow. */
return false;
}
*value = c - '0' + *value * 8;
}
else if (c == ' ' || c == '\0')
{
/* End of field, but disallow completely empty
fields. */
return ofs > 0;
}
else
{
/* Bad character. */
return false;
}
}
/* Field did not end in space or null byte. */
return false;
}
/* Returns true if the CNT bytes starting at BLOCK are all zero,
false otherwise. */
static bool
is_all_zeros (const char *block, size_t cnt)
{
while (cnt-- > 0)
if (*block++ != 0)
return false;
return true;
}
/* Parses HEADER as a ustar-format archive header for a regular
file or directory. If successful, stores the archived file's
name in *FILE_NAME (as a pointer into HEADER or a string
literal), its type in *TYPE, and its size in bytes in *SIZE,
and returns a null pointer. On failure, returns a
human-readable error message. */
const char *
ustar_parse_header (const char header[USTAR_HEADER_SIZE],
const char **file_name, enum ustar_type *type, int *size)
{
const struct ustar_header *h = (const struct ustar_header *) header;
unsigned long int chksum, size_ul;
ASSERT (sizeof (struct ustar_header) == USTAR_HEADER_SIZE);
/* Detect end of archive. */
if (is_all_zeros (header, USTAR_HEADER_SIZE))
{
*file_name = NULL;
*type = USTAR_EOF;
*size = 0;
return NULL;
}
/* Validate ustar header. */
if (memcmp (h->magic, "ustar", 6))
return "not a ustar archive";
else if (h->version[0] != '0' || h->version[1] != '0')
return "invalid ustar version";
else if (!parse_octal_field (h->chksum, sizeof h->chksum, &chksum))
return "corrupt chksum field";
else if (chksum != calculate_chksum (h))
return "checksum mismatch";
else if (h->name[sizeof h->name - 1] != '\0' || h->prefix[0] != '\0')
return "file name too long";
else if (h->typeflag != USTAR_REGULAR && h->typeflag != USTAR_DIRECTORY)
return "unimplemented file type";
if (h->typeflag == USTAR_REGULAR)
{
if (!parse_octal_field (h->size, sizeof h->size, &size_ul))
return "corrupt file size field";
else if (size_ul > INT_MAX)
return "file too large";
}
else
size_ul = 0;
/* Success. */
*file_name = strip_antisocial_prefixes (h->name);
*type = h->typeflag;
*size = size_ul;
return NULL;
}
| 10cm | trunk/10cm/pintos/src/lib/ustar.c | C | oos | 7,828 |
#include <ctype.h>
#include <debug.h>
#include <random.h>
#include <stdlib.h>
#include <stdbool.h>
/* Converts a string representation of a signed decimal integer
in S into an `int', which is returned. */
int
atoi (const char *s)
{
bool negative;
int value;
ASSERT (s != NULL);
/* Skip white space. */
while (isspace ((unsigned char) *s))
s++;
/* Parse sign. */
negative = false;
if (*s == '+')
s++;
else if (*s == '-')
{
negative = true;
s++;
}
/* Parse digits. We always initially parse the value as
negative, and then make it positive later, because the
negative range of an int is bigger than the positive range
on a 2's complement system. */
for (value = 0; isdigit (*s); s++)
value = value * 10 - (*s - '0');
if (!negative)
value = -value;
return value;
}
/* Compares A and B by calling the AUX function. */
static int
compare_thunk (const void *a, const void *b, void *aux)
{
int (**compare) (const void *, const void *) = aux;
return (*compare) (a, b);
}
/* Sorts ARRAY, which contains CNT elements of SIZE bytes each,
using COMPARE. When COMPARE is passed a pair of elements A
and B, respectively, it must return a strcmp()-type result,
i.e. less than zero if A < B, zero if A == B, greater than
zero if A > B. Runs in O(n lg n) time and O(1) space in
CNT. */
void
qsort (void *array, size_t cnt, size_t size,
int (*compare) (const void *, const void *))
{
sort (array, cnt, size, compare_thunk, &compare);
}
/* Swaps elements with 1-based indexes A_IDX and B_IDX in ARRAY
with elements of SIZE bytes each. */
static void
do_swap (unsigned char *array, size_t a_idx, size_t b_idx, size_t size)
{
unsigned char *a = array + (a_idx - 1) * size;
unsigned char *b = array + (b_idx - 1) * size;
size_t i;
for (i = 0; i < size; i++)
{
unsigned char t = a[i];
a[i] = b[i];
b[i] = t;
}
}
/* Compares elements with 1-based indexes A_IDX and B_IDX in
ARRAY with elements of SIZE bytes each, using COMPARE to
compare elements, passing AUX as auxiliary data, and returns a
strcmp()-type result. */
static int
do_compare (unsigned char *array, size_t a_idx, size_t b_idx, size_t size,
int (*compare) (const void *, const void *, void *aux),
void *aux)
{
return compare (array + (a_idx - 1) * size, array + (b_idx - 1) * size, aux);
}
/* "Float down" the element with 1-based index I in ARRAY of CNT
elements of SIZE bytes each, using COMPARE to compare
elements, passing AUX as auxiliary data. */
static void
heapify (unsigned char *array, size_t i, size_t cnt, size_t size,
int (*compare) (const void *, const void *, void *aux),
void *aux)
{
for (;;)
{
/* Set `max' to the index of the largest element among I
and its children (if any). */
size_t left = 2 * i;
size_t right = 2 * i + 1;
size_t max = i;
if (left <= cnt && do_compare (array, left, max, size, compare, aux) > 0)
max = left;
if (right <= cnt
&& do_compare (array, right, max, size, compare, aux) > 0)
max = right;
/* If the maximum value is already in element I, we're
done. */
if (max == i)
break;
/* Swap and continue down the heap. */
do_swap (array, i, max, size);
i = max;
}
}
/* Sorts ARRAY, which contains CNT elements of SIZE bytes each,
using COMPARE to compare elements, passing AUX as auxiliary
data. When COMPARE is passed a pair of elements A and B,
respectively, it must return a strcmp()-type result, i.e. less
than zero if A < B, zero if A == B, greater than zero if A >
B. Runs in O(n lg n) time and O(1) space in CNT. */
void
sort (void *array, size_t cnt, size_t size,
int (*compare) (const void *, const void *, void *aux),
void *aux)
{
size_t i;
ASSERT (array != NULL || cnt == 0);
ASSERT (compare != NULL);
ASSERT (size > 0);
/* Build a heap. */
for (i = cnt / 2; i > 0; i--)
heapify (array, i, cnt, size, compare, aux);
/* Sort the heap. */
for (i = cnt; i > 1; i--)
{
do_swap (array, 1, i, size);
heapify (array, 1, i - 1, size, compare, aux);
}
}
/* Searches ARRAY, which contains CNT elements of SIZE bytes
each, for the given KEY. Returns a match is found, otherwise
a null pointer. If there are multiple matches, returns an
arbitrary one of them.
ARRAY must be sorted in order according to COMPARE.
Uses COMPARE to compare elements. When COMPARE is passed a
pair of elements A and B, respectively, it must return a
strcmp()-type result, i.e. less than zero if A < B, zero if A
== B, greater than zero if A > B. */
void *
bsearch (const void *key, const void *array, size_t cnt,
size_t size, int (*compare) (const void *, const void *))
{
return binary_search (key, array, cnt, size, compare_thunk, &compare);
}
/* Searches ARRAY, which contains CNT elements of SIZE bytes
each, for the given KEY. Returns a match is found, otherwise
a null pointer. If there are multiple matches, returns an
arbitrary one of them.
ARRAY must be sorted in order according to COMPARE.
Uses COMPARE to compare elements, passing AUX as auxiliary
data. When COMPARE is passed a pair of elements A and B,
respectively, it must return a strcmp()-type result, i.e. less
than zero if A < B, zero if A == B, greater than zero if A >
B. */
void *
binary_search (const void *key, const void *array, size_t cnt, size_t size,
int (*compare) (const void *, const void *, void *aux),
void *aux)
{
const unsigned char *first = array;
const unsigned char *last = array + size * cnt;
while (first < last)
{
size_t range = (last - first) / size;
const unsigned char *middle = first + (range / 2) * size;
int cmp = compare (key, middle, aux);
if (cmp < 0)
last = middle;
else if (cmp > 0)
first = middle + size;
else
return (void *) middle;
}
return NULL;
}
| 10cm | trunk/10cm/pintos/src/lib/stdlib.c | C | oos | 6,133 |
#ifndef __LIB_USTAR_H
#define __LIB_USTAR_H
/* Support for the standard Posix "ustar" format. See the
documentation of the "pax" utility in [SUSv3] for the the
"ustar" format specification. */
#include <stdbool.h>
/* Type of a file entry in an archive.
The values here are the bytes that appear in the file format.
Only types of interest to Pintos are listed here. */
enum ustar_type
{
USTAR_REGULAR = '0', /* Ordinary file. */
USTAR_DIRECTORY = '5', /* Directory. */
USTAR_EOF = -1 /* End of archive (not an official value). */
};
/* Size of a ustar archive header, in bytes. */
#define USTAR_HEADER_SIZE 512
bool ustar_make_header (const char *file_name, enum ustar_type,
int size, char header[USTAR_HEADER_SIZE]);
const char *ustar_parse_header (const char header[USTAR_HEADER_SIZE],
const char **file_name,
enum ustar_type *, int *size);
#endif /* lib/ustar.h */
| 10cm | trunk/10cm/pintos/src/lib/ustar.h | C | oos | 1,015 |
#include <string.h>
#include <debug.h>
/* Copies SIZE bytes from SRC to DST, which must not overlap.
Returns DST. */
void *
memcpy (void *dst_, const void *src_, size_t size)
{
unsigned char *dst = dst_;
const unsigned char *src = src_;
ASSERT (dst != NULL || size == 0);
ASSERT (src != NULL || size == 0);
while (size-- > 0)
*dst++ = *src++;
return dst_;
}
/* Copies SIZE bytes from SRC to DST, which are allowed to
overlap. Returns DST. */
void *
memmove (void *dst_, const void *src_, size_t size)
{
unsigned char *dst = dst_;
const unsigned char *src = src_;
ASSERT (dst != NULL || size == 0);
ASSERT (src != NULL || size == 0);
if (dst < src)
{
while (size-- > 0)
*dst++ = *src++;
}
else
{
dst += size;
src += size;
while (size-- > 0)
*--dst = *--src;
}
return dst;
}
/* Find the first differing byte in the two blocks of SIZE bytes
at A and B. Returns a positive value if the byte in A is
greater, a negative value if the byte in B is greater, or zero
if blocks A and B are equal. */
int
memcmp (const void *a_, const void *b_, size_t size)
{
const unsigned char *a = a_;
const unsigned char *b = b_;
ASSERT (a != NULL || size == 0);
ASSERT (b != NULL || size == 0);
for (; size-- > 0; a++, b++)
if (*a != *b)
return *a > *b ? +1 : -1;
return 0;
}
/* Finds the first differing characters in strings A and B.
Returns a positive value if the character in A (as an unsigned
char) is greater, a negative value if the character in B (as
an unsigned char) is greater, or zero if strings A and B are
equal. */
int
strcmp (const char *a_, const char *b_)
{
const unsigned char *a = (const unsigned char *) a_;
const unsigned char *b = (const unsigned char *) b_;
ASSERT (a != NULL);
ASSERT (b != NULL);
while (*a != '\0' && *a == *b)
{
a++;
b++;
}
return *a < *b ? -1 : *a > *b;
}
/* Returns a pointer to the first occurrence of CH in the first
SIZE bytes starting at BLOCK. Returns a null pointer if CH
does not occur in BLOCK. */
void *
memchr (const void *block_, int ch_, size_t size)
{
const unsigned char *block = block_;
unsigned char ch = ch_;
ASSERT (block != NULL || size == 0);
for (; size-- > 0; block++)
if (*block == ch)
return (void *) block;
return NULL;
}
/* Finds and returns the first occurrence of C in STRING, or a
null pointer if C does not appear in STRING. If C == '\0'
then returns a pointer to the null terminator at the end of
STRING. */
char *
strchr (const char *string, int c_)
{
char c = c_;
ASSERT (string != NULL);
for (;;)
if (*string == c)
return (char *) string;
else if (*string == '\0')
return NULL;
else
string++;
}
/* Returns the length of the initial substring of STRING that
consists of characters that are not in STOP. */
size_t
strcspn (const char *string, const char *stop)
{
size_t length;
for (length = 0; string[length] != '\0'; length++)
if (strchr (stop, string[length]) != NULL)
break;
return length;
}
/* Returns a pointer to the first character in STRING that is
also in STOP. If no character in STRING is in STOP, returns a
null pointer. */
char *
strpbrk (const char *string, const char *stop)
{
for (; *string != '\0'; string++)
if (strchr (stop, *string) != NULL)
return (char *) string;
return NULL;
}
/* Returns a pointer to the last occurrence of C in STRING.
Returns a null pointer if C does not occur in STRING. */
char *
strrchr (const char *string, int c_)
{
char c = c_;
const char *p = NULL;
for (; *string != '\0'; string++)
if (*string == c)
p = string;
return (char *) p;
}
/* Returns the length of the initial substring of STRING that
consists of characters in SKIP. */
size_t
strspn (const char *string, const char *skip)
{
size_t length;
for (length = 0; string[length] != '\0'; length++)
if (strchr (skip, string[length]) == NULL)
break;
return length;
}
/* Returns a pointer to the first occurrence of NEEDLE within
HAYSTACK. Returns a null pointer if NEEDLE does not exist
within HAYSTACK. */
char *
strstr (const char *haystack, const char *needle)
{
size_t haystack_len = strlen (haystack);
size_t needle_len = strlen (needle);
if (haystack_len >= needle_len)
{
size_t i;
for (i = 0; i <= haystack_len - needle_len; i++)
if (!memcmp (haystack + i, needle, needle_len))
return (char *) haystack + i;
}
return NULL;
}
/* Breaks a string into tokens separated by DELIMITERS. The
first time this function is called, S should be the string to
tokenize, and in subsequent calls it must be a null pointer.
SAVE_PTR is the address of a `char *' variable used to keep
track of the tokenizer's position. The return value each time
is the next token in the string, or a null pointer if no
tokens remain.
This function treats multiple adjacent delimiters as a single
delimiter. The returned tokens will never be length 0.
DELIMITERS may change from one call to the next within a
single string.
strtok_r() modifies the string S, changing delimiters to null
bytes. Thus, S must be a modifiable string. String literals,
in particular, are *not* modifiable in C, even though for
backward compatibility they are not `const'.
Example usage:
char s[] = " String to tokenize. ";
char *token, *save_ptr;
for (token = strtok_r (s, " ", &save_ptr); token != NULL;
token = strtok_r (NULL, " ", &save_ptr))
printf ("'%s'\n", token);
outputs:
'String'
'to'
'tokenize.'
*/
char *
strtok_r (char *s, const char *delimiters, char **save_ptr)
{
char *token;
ASSERT (delimiters != NULL);
ASSERT (save_ptr != NULL);
/* If S is nonnull, start from it.
If S is null, start from saved position. */
if (s == NULL)
s = *save_ptr;
ASSERT (s != NULL);
/* Skip any DELIMITERS at our current position. */
while (strchr (delimiters, *s) != NULL)
{
/* strchr() will always return nonnull if we're searching
for a null byte, because every string contains a null
byte (at the end). */
if (*s == '\0')
{
*save_ptr = s;
return NULL;
}
s++;
}
/* Skip any non-DELIMITERS up to the end of the string. */
token = s;
while (strchr (delimiters, *s) == NULL)
s++;
if (*s != '\0')
{
*s = '\0';
*save_ptr = s + 1;
}
else
*save_ptr = s;
return token;
}
/* Sets the SIZE bytes in DST to VALUE. */
void *
memset (void *dst_, int value, size_t size)
{
unsigned char *dst = dst_;
ASSERT (dst != NULL || size == 0);
while (size-- > 0)
*dst++ = value;
return dst_;
}
/* Returns the length of STRING. */
size_t
strlen (const char *string)
{
const char *p;
ASSERT (string != NULL);
for (p = string; *p != '\0'; p++)
continue;
return p - string;
}
/* If STRING is less than MAXLEN characters in length, returns
its actual length. Otherwise, returns MAXLEN. */
size_t
strnlen (const char *string, size_t maxlen)
{
size_t length;
for (length = 0; string[length] != '\0' && length < maxlen; length++)
continue;
return length;
}
/* Copies string SRC to DST. If SRC is longer than SIZE - 1
characters, only SIZE - 1 characters are copied. A null
terminator is always written to DST, unless SIZE is 0.
Returns the length of SRC, not including the null terminator.
strlcpy() is not in the standard C library, but it is an
increasingly popular extension. See
http://www.courtesan.com/todd/papers/strlcpy.html for
information on strlcpy(). */
size_t
strlcpy (char *dst, const char *src, size_t size)
{
size_t src_len;
ASSERT (dst != NULL);
ASSERT (src != NULL);
src_len = strlen (src);
if (size > 0)
{
size_t dst_len = size - 1;
if (src_len < dst_len)
dst_len = src_len;
memcpy (dst, src, dst_len);
dst[dst_len] = '\0';
}
return src_len;
}
/* Concatenates string SRC to DST. The concatenated string is
limited to SIZE - 1 characters. A null terminator is always
written to DST, unless SIZE is 0. Returns the length that the
concatenated string would have assuming that there was
sufficient space, not including a null terminator.
strlcat() is not in the standard C library, but it is an
increasingly popular extension. See
http://www.courtesan.com/todd/papers/strlcpy.html for
information on strlcpy(). */
size_t
strlcat (char *dst, const char *src, size_t size)
{
size_t src_len, dst_len;
ASSERT (dst != NULL);
ASSERT (src != NULL);
src_len = strlen (src);
dst_len = strlen (dst);
if (size > 0 && dst_len < size)
{
size_t copy_cnt = size - dst_len - 1;
if (src_len < copy_cnt)
copy_cnt = src_len;
memcpy (dst + dst_len, src, copy_cnt);
dst[dst_len + copy_cnt] = '\0';
}
return src_len + dst_len;
}
| 10cm | trunk/10cm/pintos/src/lib/string.c | C | oos | 9,104 |
#ifndef __LIB_STDIO_H
#define __LIB_STDIO_H
#include <debug.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
/* Include lib/user/stdio.h or lib/kernel/stdio.h, as
appropriate. */
#include_next <stdio.h>
/* Predefined file handles. */
#define STDIN_FILENO 0
#define STDOUT_FILENO 1
/* Standard functions. */
int printf (const char *, ...) PRINTF_FORMAT (1, 2);
int snprintf (char *, size_t, const char *, ...) PRINTF_FORMAT (3, 4);
int vprintf (const char *, va_list) PRINTF_FORMAT (1, 0);
int vsnprintf (char *, size_t, const char *, va_list) PRINTF_FORMAT (3, 0);
int putchar (int);
int puts (const char *);
/* Nonstandard functions. */
void hex_dump (uintptr_t ofs, const void *, size_t size, bool ascii);
/* Internal functions. */
void __vprintf (const char *format, va_list args,
void (*output) (char, void *), void *aux);
void __printf (const char *format,
void (*output) (char, void *), void *aux, ...);
/* Try to be helpful. */
#define sprintf dont_use_sprintf_use_snprintf
#define vsprintf dont_use_vsprintf_use_vsnprintf
#endif /* lib/stdio.h */
| 10cm | trunk/10cm/pintos/src/lib/stdio.h | C | oos | 1,132 |
#include "random.h"
#include <stdbool.h>
#include <stdint.h>
#include "debug.h"
/* RC4-based pseudo-random number generator (PRNG).
RC4 is a stream cipher. We're not using it here for its
cryptographic properties, but because it is easy to implement
and its output is plenty random for non-cryptographic
purposes.
See http://en.wikipedia.org/wiki/RC4_(cipher) for information
on RC4.*/
/* RC4 state. */
static uint8_t s[256]; /* S[]. */
static uint8_t s_i, s_j; /* i, j. */
/* Already initialized? */
static bool inited;
/* Swaps the bytes pointed to by A and B. */
static inline void
swap_byte (uint8_t *a, uint8_t *b)
{
uint8_t t = *a;
*a = *b;
*b = t;
}
/* Initializes or reinitializes the PRNG with the given SEED. */
void
random_init (unsigned seed)
{
uint8_t *seedp = (uint8_t *) &seed;
int i;
uint8_t j;
for (i = 0; i < 256; i++)
s[i] = i;
for (i = j = 0; i < 256; i++)
{
j += s[i] + seedp[i % sizeof seed];
swap_byte (s + i, s + j);
}
s_i = s_j = 0;
inited = true;
}
/* Writes SIZE random bytes into BUF. */
void
random_bytes (void *buf_, size_t size)
{
uint8_t *buf;
if (!inited)
random_init (0);
for (buf = buf_; size-- > 0; buf++)
{
uint8_t s_k;
s_i++;
s_j += s[s_i];
swap_byte (s + s_i, s + s_j);
s_k = s[s_i] + s[s_j];
*buf = s[s_k];
}
}
/* Returns a pseudo-random unsigned long.
Use random_ulong() % n to obtain a random number in the range
0...n (exclusive). */
unsigned long
random_ulong (void)
{
unsigned long ul;
random_bytes (&ul, sizeof ul);
return ul;
}
| 10cm | trunk/10cm/pintos/src/lib/random.c | C | oos | 1,651 |
#ifndef __LIB_RANDOM_H
#define __LIB_RANDOM_H
#include <stddef.h>
void random_init (unsigned seed);
void random_bytes (void *, size_t);
unsigned long random_ulong (void);
#endif /* lib/random.h */
| 10cm | trunk/10cm/pintos/src/lib/random.h | C | oos | 200 |
#ifndef __LIB_STDLIB_H
#define __LIB_STDLIB_H
#include <stddef.h>
/* Standard functions. */
int atoi (const char *);
void qsort (void *array, size_t cnt, size_t size,
int (*compare) (const void *, const void *));
void *bsearch (const void *key, const void *array, size_t cnt,
size_t size, int (*compare) (const void *, const void *));
/* Nonstandard functions. */
void sort (void *array, size_t cnt, size_t size,
int (*compare) (const void *, const void *, void *aux),
void *aux);
void *binary_search (const void *key, const void *array, size_t cnt,
size_t size,
int (*compare) (const void *, const void *, void *aux),
void *aux);
#endif /* lib/stdlib.h */
| 10cm | trunk/10cm/pintos/src/lib/stdlib.h | C | oos | 773 |
#ifndef __LIB_STRING_H
#define __LIB_STRING_H
#include <stddef.h>
/* Standard. */
void *memcpy (void *, const void *, size_t);
void *memmove (void *, const void *, size_t);
char *strncat (char *, const char *, size_t);
int memcmp (const void *, const void *, size_t);
int strcmp (const char *, const char *);
void *memchr (const void *, int, size_t);
char *strchr (const char *, int);
size_t strcspn (const char *, const char *);
char *strpbrk (const char *, const char *);
char *strrchr (const char *, int);
size_t strspn (const char *, const char *);
char *strstr (const char *, const char *);
void *memset (void *, int, size_t);
size_t strlen (const char *);
/* Extensions. */
size_t strlcpy (char *, const char *, size_t);
size_t strlcat (char *, const char *, size_t);
char *strtok_r (char *, const char *, char **);
size_t strnlen (const char *, size_t);
/* Try to be helpful. */
#define strcpy dont_use_strcpy_use_strlcpy
#define strncpy dont_use_strncpy_use_strlcpy
#define strcat dont_use_strcat_use_strlcat
#define strncat dont_use_strncat_use_strlcat
#define strtok dont_use_strtok_use_strtok_r
#endif /* lib/string.h */
| 10cm | trunk/10cm/pintos/src/lib/string.h | C | oos | 1,137 |
#include <stdio.h>
#include <ctype.h>
#include <inttypes.h>
#include <round.h>
#include <stdint.h>
#include <string.h>
/* Auxiliary data for vsnprintf_helper(). */
struct vsnprintf_aux
{
char *p; /* Current output position. */
int length; /* Length of output string. */
int max_length; /* Max length of output string. */
};
static void vsnprintf_helper (char, void *);
/* Like vprintf(), except that output is stored into BUFFER,
which must have space for BUF_SIZE characters. Writes at most
BUF_SIZE - 1 characters to BUFFER, followed by a null
terminator. BUFFER will always be null-terminated unless
BUF_SIZE is zero. Returns the number of characters that would
have been written to BUFFER, not including a null terminator,
had there been enough room. */
int
vsnprintf (char *buffer, size_t buf_size, const char *format, va_list args)
{
/* Set up aux data for vsnprintf_helper(). */
struct vsnprintf_aux aux;
aux.p = buffer;
aux.length = 0;
aux.max_length = buf_size > 0 ? buf_size - 1 : 0;
/* Do most of the work. */
__vprintf (format, args, vsnprintf_helper, &aux);
/* Add null terminator. */
if (buf_size > 0)
*aux.p = '\0';
return aux.length;
}
/* Helper function for vsnprintf(). */
static void
vsnprintf_helper (char ch, void *aux_)
{
struct vsnprintf_aux *aux = aux_;
if (aux->length++ < aux->max_length)
*aux->p++ = ch;
}
/* Like printf(), except that output is stored into BUFFER,
which must have space for BUF_SIZE characters. Writes at most
BUF_SIZE - 1 characters to BUFFER, followed by a null
terminator. BUFFER will always be null-terminated unless
BUF_SIZE is zero. Returns the number of characters that would
have been written to BUFFER, not including a null terminator,
had there been enough room. */
int
snprintf (char *buffer, size_t buf_size, const char *format, ...)
{
va_list args;
int retval;
va_start (args, format);
retval = vsnprintf (buffer, buf_size, format, args);
va_end (args);
return retval;
}
/* Writes formatted output to the console.
In the kernel, the console is both the video display and first
serial port.
In userspace, the console is file descriptor 1. */
int
printf (const char *format, ...)
{
va_list args;
int retval;
va_start (args, format);
retval = vprintf (format, args);
va_end (args);
return retval;
}
/* printf() formatting internals. */
/* A printf() conversion. */
struct printf_conversion
{
/* Flags. */
enum
{
MINUS = 1 << 0, /* '-' */
PLUS = 1 << 1, /* '+' */
SPACE = 1 << 2, /* ' ' */
POUND = 1 << 3, /* '#' */
ZERO = 1 << 4, /* '0' */
GROUP = 1 << 5 /* '\'' */
}
flags;
/* Minimum field width. */
int width;
/* Numeric precision.
-1 indicates no precision was specified. */
int precision;
/* Type of argument to format. */
enum
{
CHAR = 1, /* hh */
SHORT = 2, /* h */
INT = 3, /* (none) */
INTMAX = 4, /* j */
LONG = 5, /* l */
LONGLONG = 6, /* ll */
PTRDIFFT = 7, /* t */
SIZET = 8 /* z */
}
type;
};
struct integer_base
{
int base; /* Base. */
const char *digits; /* Collection of digits. */
int x; /* `x' character to use, for base 16 only. */
int group; /* Number of digits to group with ' flag. */
};
static const struct integer_base base_d = {10, "0123456789", 0, 3};
static const struct integer_base base_o = {8, "01234567", 0, 3};
static const struct integer_base base_x = {16, "0123456789abcdef", 'x', 4};
static const struct integer_base base_X = {16, "0123456789ABCDEF", 'X', 4};
static const char *parse_conversion (const char *format,
struct printf_conversion *,
va_list *);
static void format_integer (uintmax_t value, bool is_signed, bool negative,
const struct integer_base *,
const struct printf_conversion *,
void (*output) (char, void *), void *aux);
static void output_dup (char ch, size_t cnt,
void (*output) (char, void *), void *aux);
static void format_string (const char *string, int length,
struct printf_conversion *,
void (*output) (char, void *), void *aux);
void
__vprintf (const char *format, va_list args,
void (*output) (char, void *), void *aux)
{
for (; *format != '\0'; format++)
{
struct printf_conversion c;
/* Literally copy non-conversions to output. */
if (*format != '%')
{
output (*format, aux);
continue;
}
format++;
/* %% => %. */
if (*format == '%')
{
output ('%', aux);
continue;
}
/* Parse conversion specifiers. */
format = parse_conversion (format, &c, &args);
/* Do conversion. */
switch (*format)
{
case 'd':
case 'i':
{
/* Signed integer conversions. */
intmax_t value;
switch (c.type)
{
case CHAR:
value = (signed char) va_arg (args, int);
break;
case SHORT:
value = (short) va_arg (args, int);
break;
case INT:
value = va_arg (args, int);
break;
case INTMAX:
value = va_arg (args, intmax_t);
break;
case LONG:
value = va_arg (args, long);
break;
case LONGLONG:
value = va_arg (args, long long);
break;
case PTRDIFFT:
value = va_arg (args, ptrdiff_t);
break;
case SIZET:
value = va_arg (args, size_t);
if (value > SIZE_MAX / 2)
value = value - SIZE_MAX - 1;
break;
default:
NOT_REACHED ();
}
format_integer (value < 0 ? -value : value,
true, value < 0, &base_d, &c, output, aux);
}
break;
case 'o':
case 'u':
case 'x':
case 'X':
{
/* Unsigned integer conversions. */
uintmax_t value;
const struct integer_base *b;
switch (c.type)
{
case CHAR:
value = (unsigned char) va_arg (args, unsigned);
break;
case SHORT:
value = (unsigned short) va_arg (args, unsigned);
break;
case INT:
value = va_arg (args, unsigned);
break;
case INTMAX:
value = va_arg (args, uintmax_t);
break;
case LONG:
value = va_arg (args, unsigned long);
break;
case LONGLONG:
value = va_arg (args, unsigned long long);
break;
case PTRDIFFT:
value = va_arg (args, ptrdiff_t);
#if UINTMAX_MAX != PTRDIFF_MAX
value &= ((uintmax_t) PTRDIFF_MAX << 1) | 1;
#endif
break;
case SIZET:
value = va_arg (args, size_t);
break;
default:
NOT_REACHED ();
}
switch (*format)
{
case 'o': b = &base_o; break;
case 'u': b = &base_d; break;
case 'x': b = &base_x; break;
case 'X': b = &base_X; break;
default: NOT_REACHED ();
}
format_integer (value, false, false, b, &c, output, aux);
}
break;
case 'c':
{
/* Treat character as single-character string. */
char ch = va_arg (args, int);
format_string (&ch, 1, &c, output, aux);
}
break;
case 's':
{
/* String conversion. */
const char *s = va_arg (args, char *);
if (s == NULL)
s = "(null)";
/* Limit string length according to precision.
Note: if c.precision == -1 then strnlen() will get
SIZE_MAX for MAXLEN, which is just what we want. */
format_string (s, strnlen (s, c.precision), &c, output, aux);
}
break;
case 'p':
{
/* Pointer conversion.
Format pointers as %#x. */
void *p = va_arg (args, void *);
c.flags = POUND;
format_integer ((uintptr_t) p, false, false,
&base_x, &c, output, aux);
}
break;
case 'f':
case 'e':
case 'E':
case 'g':
case 'G':
case 'n':
/* We don't support floating-point arithmetic,
and %n can be part of a security hole. */
__printf ("<<no %%%c in kernel>>", output, aux, *format);
break;
default:
__printf ("<<no %%%c conversion>>", output, aux, *format);
break;
}
}
}
/* Parses conversion option characters starting at FORMAT and
initializes C appropriately. Returns the character in FORMAT
that indicates the conversion (e.g. the `d' in `%d'). Uses
*ARGS for `*' field widths and precisions. */
static const char *
parse_conversion (const char *format, struct printf_conversion *c,
va_list *args)
{
/* Parse flag characters. */
c->flags = 0;
for (;;)
{
switch (*format++)
{
case '-':
c->flags |= MINUS;
break;
case '+':
c->flags |= PLUS;
break;
case ' ':
c->flags |= SPACE;
break;
case '#':
c->flags |= POUND;
break;
case '0':
c->flags |= ZERO;
break;
case '\'':
c->flags |= GROUP;
break;
default:
format--;
goto not_a_flag;
}
}
not_a_flag:
if (c->flags & MINUS)
c->flags &= ~ZERO;
if (c->flags & PLUS)
c->flags &= ~SPACE;
/* Parse field width. */
c->width = 0;
if (*format == '*')
{
format++;
c->width = va_arg (*args, int);
}
else
{
for (; isdigit (*format); format++)
c->width = c->width * 10 + *format - '0';
}
if (c->width < 0)
{
c->width = -c->width;
c->flags |= MINUS;
}
/* Parse precision. */
c->precision = -1;
if (*format == '.')
{
format++;
if (*format == '*')
{
format++;
c->precision = va_arg (*args, int);
}
else
{
c->precision = 0;
for (; isdigit (*format); format++)
c->precision = c->precision * 10 + *format - '0';
}
if (c->precision < 0)
c->precision = -1;
}
if (c->precision >= 0)
c->flags &= ~ZERO;
/* Parse type. */
c->type = INT;
switch (*format++)
{
case 'h':
if (*format == 'h')
{
format++;
c->type = CHAR;
}
else
c->type = SHORT;
break;
case 'j':
c->type = INTMAX;
break;
case 'l':
if (*format == 'l')
{
format++;
c->type = LONGLONG;
}
else
c->type = LONG;
break;
case 't':
c->type = PTRDIFFT;
break;
case 'z':
c->type = SIZET;
break;
default:
format--;
break;
}
return format;
}
/* Performs an integer conversion, writing output to OUTPUT with
auxiliary data AUX. The integer converted has absolute value
VALUE. If IS_SIGNED is true, does a signed conversion with
NEGATIVE indicating a negative value; otherwise does an
unsigned conversion and ignores NEGATIVE. The output is done
according to the provided base B. Details of the conversion
are in C. */
static void
format_integer (uintmax_t value, bool is_signed, bool negative,
const struct integer_base *b,
const struct printf_conversion *c,
void (*output) (char, void *), void *aux)
{
char buf[64], *cp; /* Buffer and current position. */
int x; /* `x' character to use or 0 if none. */
int sign; /* Sign character or 0 if none. */
int precision; /* Rendered precision. */
int pad_cnt; /* # of pad characters to fill field width. */
int digit_cnt; /* # of digits output so far. */
/* Determine sign character, if any.
An unsigned conversion will never have a sign character,
even if one of the flags requests one. */
sign = 0;
if (is_signed)
{
if (c->flags & PLUS)
sign = negative ? '-' : '+';
else if (c->flags & SPACE)
sign = negative ? '-' : ' ';
else if (negative)
sign = '-';
}
/* Determine whether to include `0x' or `0X'.
It will only be included with a hexadecimal conversion of a
nonzero value with the # flag. */
x = (c->flags & POUND) && value ? b->x : 0;
/* Accumulate digits into buffer.
This algorithm produces digits in reverse order, so later we
will output the buffer's content in reverse. */
cp = buf;
digit_cnt = 0;
while (value > 0)
{
if ((c->flags & GROUP) && digit_cnt > 0 && digit_cnt % b->group == 0)
*cp++ = ',';
*cp++ = b->digits[value % b->base];
value /= b->base;
digit_cnt++;
}
/* Append enough zeros to match precision.
If requested precision is 0, then a value of zero is
rendered as a null string, otherwise as "0".
If the # flag is used with base 8, the result must always
begin with a zero. */
precision = c->precision < 0 ? 1 : c->precision;
while (cp - buf < precision && cp < buf + sizeof buf - 1)
*cp++ = '0';
if ((c->flags & POUND) && b->base == 8 && (cp == buf || cp[-1] != '0'))
*cp++ = '0';
/* Calculate number of pad characters to fill field width. */
pad_cnt = c->width - (cp - buf) - (x ? 2 : 0) - (sign != 0);
if (pad_cnt < 0)
pad_cnt = 0;
/* Do output. */
if ((c->flags & (MINUS | ZERO)) == 0)
output_dup (' ', pad_cnt, output, aux);
if (sign)
output (sign, aux);
if (x)
{
output ('0', aux);
output (x, aux);
}
if (c->flags & ZERO)
output_dup ('0', pad_cnt, output, aux);
while (cp > buf)
output (*--cp, aux);
if (c->flags & MINUS)
output_dup (' ', pad_cnt, output, aux);
}
/* Writes CH to OUTPUT with auxiliary data AUX, CNT times. */
static void
output_dup (char ch, size_t cnt, void (*output) (char, void *), void *aux)
{
while (cnt-- > 0)
output (ch, aux);
}
/* Formats the LENGTH characters starting at STRING according to
the conversion specified in C. Writes output to OUTPUT with
auxiliary data AUX. */
static void
format_string (const char *string, int length,
struct printf_conversion *c,
void (*output) (char, void *), void *aux)
{
int i;
if (c->width > length && (c->flags & MINUS) == 0)
output_dup (' ', c->width - length, output, aux);
for (i = 0; i < length; i++)
output (string[i], aux);
if (c->width > length && (c->flags & MINUS) != 0)
output_dup (' ', c->width - length, output, aux);
}
/* Wrapper for __vprintf() that converts varargs into a
va_list. */
void
__printf (const char *format,
void (*output) (char, void *), void *aux, ...)
{
va_list args;
va_start (args, aux);
__vprintf (format, args, output, aux);
va_end (args);
}
/* Dumps the SIZE bytes in BUF to the console as hex bytes
arranged 16 per line. Numeric offsets are also included,
starting at OFS for the first byte in BUF. If ASCII is true
then the corresponding ASCII characters are also rendered
alongside. */
void
hex_dump (uintptr_t ofs, const void *buf_, size_t size, bool ascii)
{
const uint8_t *buf = buf_;
const size_t per_line = 16; /* Maximum bytes per line. */
while (size > 0)
{
size_t start, end, n;
size_t i;
/* Number of bytes on this line. */
start = ofs % per_line;
end = per_line;
if (end - start > size)
end = start + size;
n = end - start;
/* Print line. */
printf ("%08jx ", (uintmax_t) ROUND_DOWN (ofs, per_line));
for (i = 0; i < start; i++)
printf (" ");
for (; i < end; i++)
printf ("%02hhx%c",
buf[i - start], i == per_line / 2 - 1? '-' : ' ');
if (ascii)
{
for (; i < per_line; i++)
printf (" ");
printf ("|");
for (i = 0; i < start; i++)
printf (" ");
for (; i < end; i++)
printf ("%c",
isprint (buf[i - start]) ? buf[i - start] : '.');
for (; i < per_line; i++)
printf (" ");
printf ("|");
}
printf ("\n");
ofs += n;
buf += n;
size -= n;
}
}
| 10cm | trunk/10cm/pintos/src/lib/stdio.c | C | oos | 17,704 |
#ifndef __LIB_INTTYPES_H
#define __LIB_INTTYPES_H
#include <stdint.h>
#define PRId8 "hhd"
#define PRIi8 "hhi"
#define PRIo8 "hho"
#define PRIu8 "hhu"
#define PRIx8 "hhx"
#define PRIX8 "hhX"
#define PRId16 "hd"
#define PRIi16 "hi"
#define PRIo16 "ho"
#define PRIu16 "hu"
#define PRIx16 "hx"
#define PRIX16 "hX"
#define PRId32 "d"
#define PRIi32 "i"
#define PRIo32 "o"
#define PRIu32 "u"
#define PRIx32 "x"
#define PRIX32 "X"
#define PRId64 "lld"
#define PRIi64 "lli"
#define PRIo64 "llo"
#define PRIu64 "llu"
#define PRIx64 "llx"
#define PRIX64 "llX"
#define PRIdMAX "jd"
#define PRIiMAX "ji"
#define PRIoMAX "jo"
#define PRIuMAX "ju"
#define PRIxMAX "jx"
#define PRIXMAX "jX"
#define PRIdPTR "td"
#define PRIiPTR "ti"
#define PRIoPTR "to"
#define PRIuPTR "tu"
#define PRIxPTR "tx"
#define PRIXPTR "tX"
#endif /* lib/inttypes.h */
| 10cm | trunk/10cm/pintos/src/lib/inttypes.h | C | oos | 838 |
#ifndef __LIB_LIMITS_H
#define __LIB_LIMITS_H
#define CHAR_BIT 8
#define SCHAR_MAX 127
#define SCHAR_MIN (-SCHAR_MAX - 1)
#define UCHAR_MAX 255
#ifdef __CHAR_UNSIGNED__
#define CHAR_MIN 0
#define CHAR_MAX UCHAR_MAX
#else
#define CHAR_MIN SCHAR_MIN
#define CHAR_MAX SCHAR_MAX
#endif
#define SHRT_MAX 32767
#define SHRT_MIN (-SHRT_MAX - 1)
#define USHRT_MAX 65535
#define INT_MAX 2147483647
#define INT_MIN (-INT_MAX - 1)
#define UINT_MAX 4294967295U
#define LONG_MAX 2147483647L
#define LONG_MIN (-LONG_MAX - 1)
#define ULONG_MAX 4294967295UL
#define LLONG_MAX 9223372036854775807LL
#define LLONG_MIN (-LLONG_MAX - 1)
#define ULLONG_MAX 18446744073709551615ULL
#endif /* lib/limits.h */
| 10cm | trunk/10cm/pintos/src/lib/limits.h | C | oos | 694 |
#ifndef __LIB_STDINT_H
#define __LIB_STDINT_H
typedef signed char int8_t;
#define INT8_MAX 127
#define INT8_MIN (-INT8_MAX - 1)
typedef signed short int int16_t;
#define INT16_MAX 32767
#define INT16_MIN (-INT16_MAX - 1)
typedef signed int int32_t;
#define INT32_MAX 2147483647
#define INT32_MIN (-INT32_MAX - 1)
typedef signed long long int int64_t;
#define INT64_MAX 9223372036854775807LL
#define INT64_MIN (-INT64_MAX - 1)
typedef unsigned char uint8_t;
#define UINT8_MAX 255
typedef unsigned short int uint16_t;
#define UINT16_MAX 65535
typedef unsigned int uint32_t;
#define UINT32_MAX 4294967295U
typedef unsigned long long int uint64_t;
#define UINT64_MAX 18446744073709551615ULL
typedef int32_t intptr_t;
#define INTPTR_MIN INT32_MIN
#define INTPTR_MAX INT32_MAX
typedef uint32_t uintptr_t;
#define UINTPTR_MAX UINT32_MAX
typedef int64_t intmax_t;
#define INTMAX_MIN INT64_MIN
#define INTMAX_MAX INT64_MAX
typedef uint64_t uintmax_t;
#define UINTMAX_MAX UINT64_MAX
#define PTRDIFF_MIN INT32_MIN
#define PTRDIFF_MAX INT32_MAX
#define SIZE_MAX UINT32_MAX
#endif /* lib/stdint.h */
| 10cm | trunk/10cm/pintos/src/lib/stdint.h | C | oos | 1,102 |
#include <syscall.h>
int main (int, char *[]);
void _start (int argc, char *argv[]);
void
_start (int argc, char *argv[])
{
exit (main (argc, argv));
}
| 10cm | trunk/10cm/pintos/src/lib/user/entry.c | C | oos | 157 |
#include <syscall.h>
#include "../syscall-nr.h"
/* Invokes syscall NUMBER, passing no arguments, and returns the
return value as an `int'. */
#define syscall0(NUMBER) \
({ \
int retval; \
asm volatile \
("pushl %[number]; int $0x30; addl $4, %%esp" \
: "=a" (retval) \
: [number] "i" (NUMBER) \
: "memory"); \
retval; \
})
/* Invokes syscall NUMBER, passing argument ARG0, and returns the
return value as an `int'. */
#define syscall1(NUMBER, ARG0) \
({ \
int retval; \
asm volatile \
("pushl %[arg0]; pushl %[number]; int $0x30; addl $8, %%esp" \
: "=a" (retval) \
: [number] "i" (NUMBER), \
[arg0] "g" (ARG0) \
: "memory"); \
retval; \
})
/* Invokes syscall NUMBER, passing arguments ARG0 and ARG1, and
returns the return value as an `int'. */
#define syscall2(NUMBER, ARG0, ARG1) \
({ \
int retval; \
asm volatile \
("pushl %[arg1]; pushl %[arg0]; " \
"pushl %[number]; int $0x30; addl $12, %%esp" \
: "=a" (retval) \
: [number] "i" (NUMBER), \
[arg0] "g" (ARG0), \
[arg1] "g" (ARG1) \
: "memory"); \
retval; \
})
/* Invokes syscall NUMBER, passing arguments ARG0, ARG1, and
ARG2, and returns the return value as an `int'. */
#define syscall3(NUMBER, ARG0, ARG1, ARG2) \
({ \
int retval; \
asm volatile \
("pushl %[arg2]; pushl %[arg1]; pushl %[arg0]; " \
"pushl %[number]; int $0x30; addl $16, %%esp" \
: "=a" (retval) \
: [number] "i" (NUMBER), \
[arg0] "g" (ARG0), \
[arg1] "g" (ARG1), \
[arg2] "g" (ARG2) \
: "memory"); \
retval; \
})
void
halt (void)
{
syscall0 (SYS_HALT);
NOT_REACHED ();
}
void
exit (int status)
{
syscall1 (SYS_EXIT, status);
NOT_REACHED ();
}
pid_t
exec (const char *file)
{
return (pid_t) syscall1 (SYS_EXEC, file);
}
int
wait (pid_t pid)
{
return syscall1 (SYS_WAIT, pid);
}
bool
create (const char *file, unsigned initial_size)
{
return syscall2 (SYS_CREATE, file, initial_size);
}
bool
remove (const char *file)
{
return syscall1 (SYS_REMOVE, file);
}
int
open (const char *file)
{
return syscall1 (SYS_OPEN, file);
}
int
filesize (int fd)
{
return syscall1 (SYS_FILESIZE, fd);
}
int
read (int fd, void *buffer, unsigned size)
{
return syscall3 (SYS_READ, fd, buffer, size);
}
int
write (int fd, const void *buffer, unsigned size)
{
return syscall3 (SYS_WRITE, fd, buffer, size);
}
void
seek (int fd, unsigned position)
{
syscall2 (SYS_SEEK, fd, position);
}
unsigned
tell (int fd)
{
return syscall1 (SYS_TELL, fd);
}
void
close (int fd)
{
syscall1 (SYS_CLOSE, fd);
}
mapid_t
mmap (int fd, void *addr)
{
return syscall2 (SYS_MMAP, fd, addr);
}
void
munmap (mapid_t mapid)
{
syscall1 (SYS_MUNMAP, mapid);
}
bool
chdir (const char *dir)
{
return syscall1 (SYS_CHDIR, dir);
}
bool
mkdir (const char *dir)
{
return syscall1 (SYS_MKDIR, dir);
}
bool
readdir (int fd, char name[READDIR_MAX_LEN + 1])
{
return syscall2 (SYS_READDIR, fd, name);
}
bool
isdir (int fd)
{
return syscall1 (SYS_ISDIR, fd);
}
int
inumber (int fd)
{
return syscall1 (SYS_INUMBER, fd);
}
int
timer ()
{
return syscall0 (SYS_TIMER);
}
| 10cm | trunk/10cm/pintos/src/lib/user/syscall.c | C | oos | 5,075 |
#ifndef __LIB_USER_STDIO_H
#define __LIB_USER_STDIO_H
int hprintf (int, const char *, ...) PRINTF_FORMAT (2, 3);
int vhprintf (int, const char *, va_list) PRINTF_FORMAT (2, 0);
#endif /* lib/user/stdio.h */
| 10cm | trunk/10cm/pintos/src/lib/user/stdio.h | C | oos | 209 |
#ifndef __LIB_USER_SYSCALL_H
#define __LIB_USER_SYSCALL_H
#include <stdbool.h>
#include <debug.h>
/* Process identifier. */
typedef int pid_t;
#define PID_ERROR ((pid_t) -1)
/* Map region identifier. */
typedef int mapid_t;
#define MAP_FAILED ((mapid_t) -1)
/* Maximum characters in a filename written by readdir(). */
#define READDIR_MAX_LEN 14
/* Typical return values from main() and arguments to exit(). */
#define EXIT_SUCCESS 0 /* Successful execution. */
#define EXIT_FAILURE 1 /* Unsuccessful execution. */
/* Projects 2 and later. */
void halt (void) NO_RETURN;
void exit (int status) NO_RETURN;
pid_t exec (const char *file);
int wait (pid_t);
bool create (const char *file, unsigned initial_size);
bool remove (const char *file);
int open (const char *file);
int filesize (int fd);
int read (int fd, void *buffer, unsigned length);
int write (int fd, const void *buffer, unsigned length);
void seek (int fd, unsigned position);
unsigned tell (int fd);
void close (int fd);
/* Project 3 and optionally project 4. */
mapid_t mmap (int fd, void *addr);
void munmap (mapid_t);
/* Project 4 only. */
bool chdir (const char *dir);
bool mkdir (const char *dir);
bool readdir (int fd, char name[READDIR_MAX_LEN + 1]);
bool isdir (int fd);
int inumber (int fd);
int timer (void);
#endif /* lib/user/syscall.h */
| 10cm | trunk/10cm/pintos/src/lib/user/syscall.h | C | oos | 1,341 |
#include <stdio.h>
#include <string.h>
#include <syscall.h>
#include <syscall-nr.h>
/* The standard vprintf() function,
which is like printf() but uses a va_list. */
int
vprintf (const char *format, va_list args)
{
return vhprintf (STDOUT_FILENO, format, args);
}
/* Like printf(), but writes output to the given HANDLE. */
int
hprintf (int handle, const char *format, ...)
{
va_list args;
int retval;
va_start (args, format);
retval = vhprintf (handle, format, args);
va_end (args);
return retval;
}
/* Writes string S to the console, followed by a new-line
character. */
int
puts (const char *s)
{
write (STDOUT_FILENO, s, strlen (s));
putchar ('\n');
return 0;
}
/* Writes C to the console. */
int
putchar (int c)
{
char c2 = c;
write (STDOUT_FILENO, &c2, 1);
return c;
}
/* Auxiliary data for vhprintf_helper(). */
struct vhprintf_aux
{
char buf[64]; /* Character buffer. */
char *p; /* Current position in buffer. */
int char_cnt; /* Total characters written so far. */
int handle; /* Output file handle. */
};
static void add_char (char, void *);
static void flush (struct vhprintf_aux *);
/* Formats the printf() format specification FORMAT with
arguments given in ARGS and writes the output to the given
HANDLE. */
int
vhprintf (int handle, const char *format, va_list args)
{
struct vhprintf_aux aux;
aux.p = aux.buf;
aux.char_cnt = 0;
aux.handle = handle;
__vprintf (format, args, add_char, &aux);
flush (&aux);
return aux.char_cnt;
}
/* Adds C to the buffer in AUX, flushing it if the buffer fills
up. */
static void
add_char (char c, void *aux_)
{
struct vhprintf_aux *aux = aux_;
*aux->p++ = c;
if (aux->p >= aux->buf + sizeof aux->buf)
flush (aux);
aux->char_cnt++;
}
/* Flushes the buffer in AUX. */
static void
flush (struct vhprintf_aux *aux)
{
if (aux->p > aux->buf)
write (aux->handle, aux->buf, aux->p - aux->buf);
aux->p = aux->buf;
}
| 10cm | trunk/10cm/pintos/src/lib/user/console.c | C | oos | 2,002 |
#include <debug.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <syscall.h>
/* Aborts the user program, printing the source file name, line
number, and function name, plus a user-specific message. */
void
debug_panic (const char *file, int line, const char *function,
const char *message, ...)
{
va_list args;
printf ("User process ABORT at %s:%d in %s(): ", file, line, function);
va_start (args, message);
vprintf (message, args);
printf ("\n");
va_end (args);
debug_backtrace ();
exit (1);
}
| 10cm | trunk/10cm/pintos/src/lib/user/debug.c | C | oos | 558 |
#ifndef __LIB_ROUND_H
#define __LIB_ROUND_H
/* Yields X rounded up to the nearest multiple of STEP.
For X >= 0, STEP >= 1 only. */
#define ROUND_UP(X, STEP) (((X) + (STEP) - 1) / (STEP) * (STEP))
/* Yields X divided by STEP, rounded up.
For X >= 0, STEP >= 1 only. */
#define DIV_ROUND_UP(X, STEP) (((X) + (STEP) - 1) / (STEP))
/* Yields X rounded down to the nearest multiple of STEP.
For X >= 0, STEP >= 1 only. */
#define ROUND_DOWN(X, STEP) ((X) / (STEP) * (STEP))
/* There is no DIV_ROUND_DOWN. It would be simply X / STEP. */
#endif /* lib/round.h */
| 10cm | trunk/10cm/pintos/src/lib/round.h | C | oos | 573 |
#ifndef __LIB_CTYPE_H
#define __LIB_CTYPE_H
static inline int islower (int c) { return c >= 'a' && c <= 'z'; }
static inline int isupper (int c) { return c >= 'A' && c <= 'Z'; }
static inline int isalpha (int c) { return islower (c) || isupper (c); }
static inline int isdigit (int c) { return c >= '0' && c <= '9'; }
static inline int isalnum (int c) { return isalpha (c) || isdigit (c); }
static inline int isxdigit (int c) {
return isdigit (c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
}
static inline int isspace (int c) {
return (c == ' ' || c == '\f' || c == '\n'
|| c == '\r' || c == '\t' || c == '\v');
}
static inline int isblank (int c) { return c == ' ' || c == '\t'; }
static inline int isgraph (int c) { return c > 32 && c < 127; }
static inline int isprint (int c) { return c >= 32 && c < 127; }
static inline int iscntrl (int c) { return (c >= 0 && c < 32) || c == 127; }
static inline int isascii (int c) { return c >= 0 && c < 128; }
static inline int ispunct (int c) {
return isprint (c) && !isalnum (c) && !isspace (c);
}
static inline int tolower (int c) { return isupper (c) ? c - 'A' + 'a' : c; }
static inline int toupper (int c) { return islower (c) ? c - 'a' + 'A' : c; }
#endif /* lib/ctype.h */
| 10cm | trunk/10cm/pintos/src/lib/ctype.h | C | oos | 1,252 |
#ifndef __LIB_STDDEF_H
#define __LIB_STDDEF_H
#define NULL ((void *) 0)
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *) 0)->MEMBER)
/* GCC predefines the types we need for ptrdiff_t and size_t,
so that we don't have to guess. */
typedef __PTRDIFF_TYPE__ ptrdiff_t;
typedef __SIZE_TYPE__ size_t;
#endif /* lib/stddef.h */
| 10cm | trunk/10cm/pintos/src/lib/stddef.h | C | oos | 331 |
#ifndef __LIB_SYSCALL_NR_H
#define __LIB_SYSCALL_NR_H
/* System call numbers. */
enum
{
/* Projects 2 and later. */
SYS_HALT, /* Halt the operating system. */
SYS_EXIT, /* Terminate this process. */
SYS_EXEC, /* Start another process. */
SYS_WAIT, /* Wait for a child process to die. */
SYS_CREATE, /* Create a file. */
SYS_REMOVE, /* Delete a file. */
SYS_OPEN, /* Open a file. */
SYS_FILESIZE, /* Obtain a file's size. */
SYS_READ, /* Read from a file. */
SYS_WRITE, /* Write to a file. */
SYS_SEEK, /* Change position in a file. */
SYS_TELL, /* Report current position in a file. */
SYS_CLOSE, /* Close a file. */
/* Project 3 and optionally project 4. */
SYS_MMAP, /* Map a file into memory. */
SYS_MUNMAP, /* Remove a memory mapping. */
/* Project 4 only. */
SYS_CHDIR, /* Change the current directory. */
SYS_MKDIR, /* Create a directory. */
SYS_READDIR, /* Reads a directory entry. */
SYS_ISDIR, /* Tests if a fd represents a directory. */
SYS_INUMBER, /* Returns the inode number for a fd. */
SYS_TIMER
};
#endif /* lib/syscall-nr.h */
| 10cm | trunk/10cm/pintos/src/lib/syscall-nr.h | C | oos | 1,489 |
#include <debug.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
/* Prints the call stack, that is, a list of addresses, one in
each of the functions we are nested within. gdb or addr2line
may be applied to kernel.o to translate these into file names,
line numbers, and function names. */
void
debug_backtrace (void)
{
static bool explained;
void **frame;
printf ("Call stack:");
for (frame = __builtin_frame_address (0);
frame != NULL && frame[0] != NULL;
frame = frame[0])
printf (" %p", frame[1]);
printf (".\n");
if (!explained)
{
explained = true;
printf ("The `backtrace' program can make call stacks useful.\n"
"Read \"Backtraces\" in the \"Debugging Tools\" chapter\n"
"of the Pintos documentation for more information.\n");
}
}
| 10cm | trunk/10cm/pintos/src/lib/debug.c | C | oos | 888 |
#include <stdint.h>
/* On x86, division of one 64-bit integer by another cannot be
done with a single instruction or a short sequence. Thus, GCC
implements 64-bit division and remainder operations through
function calls. These functions are normally obtained from
libgcc, which is automatically included by GCC in any link
that it does.
Some x86-64 machines, however, have a compiler and utilities
that can generate 32-bit x86 code without having any of the
necessary libraries, including libgcc. Thus, we can make
Pintos work on these machines by simply implementing our own
64-bit division routines, which are the only routines from
libgcc that Pintos requires.
Completeness is another reason to include these routines. If
Pintos is completely self-contained, then that makes it that
much less mysterious. */
/* Uses x86 DIVL instruction to divide 64-bit N by 32-bit D to
yield a 32-bit quotient. Returns the quotient.
Traps with a divide error (#DE) if the quotient does not fit
in 32 bits. */
static inline uint32_t
divl (uint64_t n, uint32_t d)
{
uint32_t n1 = n >> 32;
uint32_t n0 = n;
uint32_t q, r;
asm ("divl %4"
: "=d" (r), "=a" (q)
: "0" (n1), "1" (n0), "rm" (d));
return q;
}
/* Returns the number of leading zero bits in X,
which must be nonzero. */
static int
nlz (uint32_t x)
{
/* This technique is portable, but there are better ways to do
it on particular systems. With sufficiently new enough GCC,
you can use __builtin_clz() to take advantage of GCC's
knowledge of how to do it. Or you can use the x86 BSR
instruction directly. */
int n = 0;
if (x <= 0x0000FFFF)
{
n += 16;
x <<= 16;
}
if (x <= 0x00FFFFFF)
{
n += 8;
x <<= 8;
}
if (x <= 0x0FFFFFFF)
{
n += 4;
x <<= 4;
}
if (x <= 0x3FFFFFFF)
{
n += 2;
x <<= 2;
}
if (x <= 0x7FFFFFFF)
n++;
return n;
}
/* Divides unsigned 64-bit N by unsigned 64-bit D and returns the
quotient. */
static uint64_t
udiv64 (uint64_t n, uint64_t d)
{
if ((d >> 32) == 0)
{
/* Proof of correctness:
Let n, d, b, n1, and n0 be defined as in this function.
Let [x] be the "floor" of x. Let T = b[n1/d]. Assume d
nonzero. Then:
[n/d] = [n/d] - T + T
= [n/d - T] + T by (1) below
= [(b*n1 + n0)/d - T] + T by definition of n
= [(b*n1 + n0)/d - dT/d] + T
= [(b(n1 - d[n1/d]) + n0)/d] + T
= [(b[n1 % d] + n0)/d] + T, by definition of %
which is the expression calculated below.
(1) Note that for any real x, integer i: [x] + i = [x + i].
To prevent divl() from trapping, [(b[n1 % d] + n0)/d] must
be less than b. Assume that [n1 % d] and n0 take their
respective maximum values of d - 1 and b - 1:
[(b(d - 1) + (b - 1))/d] < b
<=> [(bd - 1)/d] < b
<=> [b - 1/d] < b
which is a tautology.
Therefore, this code is correct and will not trap. */
uint64_t b = 1ULL << 32;
uint32_t n1 = n >> 32;
uint32_t n0 = n;
uint32_t d0 = d;
return divl (b * (n1 % d0) + n0, d0) + b * (n1 / d0);
}
else
{
/* Based on the algorithm and proof available from
http://www.hackersdelight.org/revisions.pdf. */
if (n < d)
return 0;
else
{
uint32_t d1 = d >> 32;
int s = nlz (d1);
uint64_t q = divl (n >> 1, (d << s) >> 32) >> (31 - s);
return n - (q - 1) * d < d ? q - 1 : q;
}
}
}
/* Divides unsigned 64-bit N by unsigned 64-bit D and returns the
remainder. */
static uint32_t
umod64 (uint64_t n, uint64_t d)
{
return n - d * udiv64 (n, d);
}
/* Divides signed 64-bit N by signed 64-bit D and returns the
quotient. */
static int64_t
sdiv64 (int64_t n, int64_t d)
{
uint64_t n_abs = n >= 0 ? (uint64_t) n : -(uint64_t) n;
uint64_t d_abs = d >= 0 ? (uint64_t) d : -(uint64_t) d;
uint64_t q_abs = udiv64 (n_abs, d_abs);
return (n < 0) == (d < 0) ? (int64_t) q_abs : -(int64_t) q_abs;
}
/* Divides signed 64-bit N by signed 64-bit D and returns the
remainder. */
static int32_t
smod64 (int64_t n, int64_t d)
{
return n - d * sdiv64 (n, d);
}
/* These are the routines that GCC calls. */
long long __divdi3 (long long n, long long d);
long long __moddi3 (long long n, long long d);
unsigned long long __udivdi3 (unsigned long long n, unsigned long long d);
unsigned long long __umoddi3 (unsigned long long n, unsigned long long d);
/* Signed 64-bit division. */
long long
__divdi3 (long long n, long long d)
{
return sdiv64 (n, d);
}
/* Signed 64-bit remainder. */
long long
__moddi3 (long long n, long long d)
{
return smod64 (n, d);
}
/* Unsigned 64-bit division. */
unsigned long long
__udivdi3 (unsigned long long n, unsigned long long d)
{
return udiv64 (n, d);
}
/* Unsigned 64-bit remainder. */
unsigned long long
__umoddi3 (unsigned long long n, unsigned long long d)
{
return umod64 (n, d);
}
| 10cm | trunk/10cm/pintos/src/lib/arithmetic.c | C | oos | 5,229 |
#ifndef __LIB_KERNEL_BITMAP_H
#define __LIB_KERNEL_BITMAP_H
#include <stdbool.h>
#include <stddef.h>
#include <inttypes.h>
/* Bitmap abstract data type. */
/* Creation and destruction. */
struct bitmap *bitmap_create (size_t bit_cnt);
struct bitmap *bitmap_create_in_buf (size_t bit_cnt, void *, size_t byte_cnt);
size_t bitmap_buf_size (size_t bit_cnt);
void bitmap_destroy (struct bitmap *);
/* Bitmap size. */
size_t bitmap_size (const struct bitmap *);
/* Setting and testing single bits. */
void bitmap_set (struct bitmap *, size_t idx, bool);
void bitmap_mark (struct bitmap *, size_t idx);
void bitmap_reset (struct bitmap *, size_t idx);
void bitmap_flip (struct bitmap *, size_t idx);
bool bitmap_test (const struct bitmap *, size_t idx);
/* Setting and testing multiple bits. */
void bitmap_set_all (struct bitmap *, bool);
void bitmap_set_multiple (struct bitmap *, size_t start, size_t cnt, bool);
size_t bitmap_count (const struct bitmap *, size_t start, size_t cnt, bool);
bool bitmap_contains (const struct bitmap *, size_t start, size_t cnt, bool);
bool bitmap_any (const struct bitmap *, size_t start, size_t cnt);
bool bitmap_none (const struct bitmap *, size_t start, size_t cnt);
bool bitmap_all (const struct bitmap *, size_t start, size_t cnt);
/* Finding set or unset bits. */
#define BITMAP_ERROR SIZE_MAX
size_t bitmap_scan (const struct bitmap *, size_t start, size_t cnt, bool);
size_t bitmap_scan_and_flip (struct bitmap *, size_t start, size_t cnt, bool);
/* File input and output. */
#ifdef FILESYS
struct file;
size_t bitmap_file_size (const struct bitmap *);
bool bitmap_read (struct bitmap *, struct file *);
bool bitmap_write (const struct bitmap *, struct file *);
#endif
/* Debugging. */
void bitmap_dump (const struct bitmap *);
#endif /* lib/kernel/bitmap.h */
| 10cm | trunk/10cm/pintos/src/lib/kernel/bitmap.h | C | oos | 1,809 |
#ifndef __LIB_KERNEL_HASH_H
#define __LIB_KERNEL_HASH_H
/* Hash table.
This data structure is thoroughly documented in the Tour of
Pintos for Project 3.
This is a standard hash table with chaining. To locate an
element in the table, we compute a hash function over the
element's data and use that as an index into an array of
doubly linked lists, then linearly search the list.
The chain lists do not use dynamic allocation. Instead, each
structure that can potentially be in a hash must embed a
struct hash_elem member. All of the hash functions operate on
these `struct hash_elem's. The hash_entry macro allows
conversion from a struct hash_elem back to a structure object
that contains it. This is the same technique used in the
linked list implementation. Refer to lib/kernel/list.h for a
detailed explanation. */
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "list.h"
/* Hash element. */
struct hash_elem
{
struct list_elem list_elem;
};
/* Converts pointer to hash element HASH_ELEM into a pointer to
the structure that HASH_ELEM is embedded inside. Supply the
name of the outer structure STRUCT and the member name MEMBER
of the hash element. See the big comment at the top of the
file for an example. */
#define hash_entry(HASH_ELEM, STRUCT, MEMBER) \
((STRUCT *) ((uint8_t *) &(HASH_ELEM)->list_elem \
- offsetof (STRUCT, MEMBER.list_elem)))
/* Computes and returns the hash value for hash element E, given
auxiliary data AUX. */
typedef unsigned hash_hash_func (const struct hash_elem *e, void *aux);
/* Compares the value of two hash elements A and B, given
auxiliary data AUX. Returns true if A is less than B, or
false if A is greater than or equal to B. */
typedef bool hash_less_func (const struct hash_elem *a,
const struct hash_elem *b,
void *aux);
/* Performs some operation on hash element E, given auxiliary
data AUX. */
typedef void hash_action_func (struct hash_elem *e, void *aux);
/* Hash table. */
struct hash
{
size_t elem_cnt; /* Number of elements in table. */
size_t bucket_cnt; /* Number of buckets, a power of 2. */
struct list *buckets; /* Array of `bucket_cnt' lists. */
hash_hash_func *hash; /* Hash function. */
hash_less_func *less; /* Comparison function. */
void *aux; /* Auxiliary data for `hash' and `less'. */
};
/* A hash table iterator. */
struct hash_iterator
{
struct hash *hash; /* The hash table. */
struct list *bucket; /* Current bucket. */
struct hash_elem *elem; /* Current hash element in current bucket. */
};
/* Basic life cycle. */
bool hash_init (struct hash *, hash_hash_func *, hash_less_func *, void *aux);
void hash_clear (struct hash *, hash_action_func *);
void hash_destroy (struct hash *, hash_action_func *);
/* Search, insertion, deletion. */
struct hash_elem *hash_insert (struct hash *, struct hash_elem *);
struct hash_elem *hash_replace (struct hash *, struct hash_elem *);
struct hash_elem *hash_find (struct hash *, struct hash_elem *);
struct hash_elem *hash_delete (struct hash *, struct hash_elem *);
/* Iteration. */
void hash_apply (struct hash *, hash_action_func *);
void hash_first (struct hash_iterator *, struct hash *);
struct hash_elem *hash_next (struct hash_iterator *);
struct hash_elem *hash_cur (struct hash_iterator *);
/* Information. */
size_t hash_size (struct hash *);
bool hash_empty (struct hash *);
/* Sample hash functions. */
unsigned hash_bytes (const void *, size_t);
unsigned hash_string (const char *);
unsigned hash_int (int);
#endif /* lib/kernel/hash.h */
| 10cm | trunk/10cm/pintos/src/lib/kernel/hash.h | C | oos | 3,821 |
#ifndef __LIB_KERNEL_STDIO_H
#define __LIB_KERNEL_STDIO_H
void putbuf (const char *, size_t);
#endif /* lib/kernel/stdio.h */
| 10cm | trunk/10cm/pintos/src/lib/kernel/stdio.h | C | oos | 128 |
#ifndef __LIB_KERNEL_LIST_H
#define __LIB_KERNEL_LIST_H
/* Doubly linked list.
This implementation of a doubly linked list does not require
use of dynamically allocated memory. Instead, each structure
that is a potential list element must embed a struct list_elem
member. All of the list functions operate on these `struct
list_elem's. The list_entry macro allows conversion from a
struct list_elem back to a structure object that contains it.
For example, suppose there is a needed for a list of `struct
foo'. `struct foo' should contain a `struct list_elem'
member, like so:
struct foo
{
struct list_elem elem;
int bar;
...other members...
};
Then a list of `struct foo' can be be declared and initialized
like so:
struct list foo_list;
list_init (&foo_list);
Iteration is a typical situation where it is necessary to
convert from a struct list_elem back to its enclosing
structure. Here's an example using foo_list:
struct list_elem *e;
for (e = list_begin (&foo_list); e != list_end (&foo_list);
e = list_next (e))
{
struct foo *f = list_entry (e, struct foo, elem);
...do something with f...
}
You can find real examples of list usage throughout the
source; for example, malloc.c, palloc.c, and thread.c in the
threads directory all use lists.
The interface for this list is inspired by the list<> template
in the C++ STL. If you're familiar with list<>, you should
find this easy to use. However, it should be emphasized that
these lists do *no* type checking and can't do much other
correctness checking. If you screw up, it will bite you.
Glossary of list terms:
- "front": The first element in a list. Undefined in an
empty list. Returned by list_front().
- "back": The last element in a list. Undefined in an empty
list. Returned by list_back().
- "tail": The element figuratively just after the last
element of a list. Well defined even in an empty list.
Returned by list_end(). Used as the end sentinel for an
iteration from front to back.
- "beginning": In a non-empty list, the front. In an empty
list, the tail. Returned by list_begin(). Used as the
starting point for an iteration from front to back.
- "head": The element figuratively just before the first
element of a list. Well defined even in an empty list.
Returned by list_rend(). Used as the end sentinel for an
iteration from back to front.
- "reverse beginning": In a non-empty list, the back. In an
empty list, the head. Returned by list_rbegin(). Used as
the starting point for an iteration from back to front.
- "interior element": An element that is not the head or
tail, that is, a real list element. An empty list does
not have any interior elements.
*/
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
/* List element. */
struct list_elem
{
struct list_elem *prev; /* Previous list element. */
struct list_elem *next; /* Next list element. */
};
/* List. */
struct list
{
struct list_elem head; /* List head. */
struct list_elem tail; /* List tail. */
};
/* Converts pointer to list element LIST_ELEM into a pointer to
the structure that LIST_ELEM is embedded inside. Supply the
name of the outer structure STRUCT and the member name MEMBER
of the list element. See the big comment at the top of the
file for an example. */
#define list_entry(LIST_ELEM, STRUCT, MEMBER) \
((STRUCT *) ((uint8_t *) &(LIST_ELEM)->next \
- offsetof (STRUCT, MEMBER.next)))
void list_init (struct list *);
/* List traversal. */
struct list_elem *list_begin (struct list *);
struct list_elem *list_next (struct list_elem *);
struct list_elem *list_end (struct list *);
struct list_elem *list_rbegin (struct list *);
struct list_elem *list_prev (struct list_elem *);
struct list_elem *list_rend (struct list *);
struct list_elem *list_head (struct list *);
struct list_elem *list_tail (struct list *);
/* List insertion. */
void list_insert (struct list_elem *, struct list_elem *);
void list_splice (struct list_elem *before,
struct list_elem *first, struct list_elem *last);
void list_push_front (struct list *, struct list_elem *);
void list_push_back (struct list *, struct list_elem *);
/* List removal. */
struct list_elem *list_remove (struct list_elem *);
struct list_elem *list_pop_front (struct list *);
struct list_elem *list_pop_back (struct list *);
/* List elements. */
struct list_elem *list_front (struct list *);
struct list_elem *list_back (struct list *);
/* List properties. */
size_t list_size (struct list *);
bool list_empty (struct list *);
/* Miscellaneous. */
void list_reverse (struct list *);
/* Compares the value of two list elements A and B, given
auxiliary data AUX. Returns true if A is less than B, or
false if A is greater than or equal to B. */
typedef bool list_less_func (const struct list_elem *a,
const struct list_elem *b,
void *aux);
/* Operations on lists with ordered elements. */
void list_sort (struct list *,
list_less_func *, void *aux);
void list_insert_ordered (struct list *, struct list_elem *,
list_less_func *, void *aux);
void list_unique (struct list *, struct list *duplicates,
list_less_func *, void *aux);
/* Max and min. */
struct list_elem *list_max (struct list *, list_less_func *, void *aux);
struct list_elem *list_min (struct list *, list_less_func *, void *aux);
/* clock처럼 돌면서 list의 다음 원소를 return */
struct list_elem * list_clock_next(struct list_elem *e, struct list *l);
#endif /* lib/kernel/list.h */
| 10cm | trunk/10cm/pintos/src/lib/kernel/list.h | C | oos | 5,998 |
/* Hash table.
This data structure is thoroughly documented in the Tour of
Pintos for Project 3.
See hash.h for basic information. */
#include "hash.h"
#include "../debug.h"
#include "threads/malloc.h"
#define list_elem_to_hash_elem(LIST_ELEM) \
list_entry(LIST_ELEM, struct hash_elem, list_elem)
static struct list *find_bucket (struct hash *, struct hash_elem *);
static struct hash_elem *find_elem (struct hash *, struct list *,
struct hash_elem *);
static void insert_elem (struct hash *, struct list *, struct hash_elem *);
static void remove_elem (struct hash *, struct hash_elem *);
static void rehash (struct hash *);
/* Initializes hash table H to compute hash values using HASH and
compare hash elements using LESS, given auxiliary data AUX. */
bool
hash_init (struct hash *h,
hash_hash_func *hash, hash_less_func *less, void *aux)
{
h->elem_cnt = 0;
h->bucket_cnt = 4;
h->buckets = malloc (sizeof *h->buckets * h->bucket_cnt);
h->hash = hash;
h->less = less;
h->aux = aux;
if (h->buckets != NULL)
{
hash_clear (h, NULL);
return true;
}
else
return false;
}
/* Removes all the elements from H.
If DESTRUCTOR is non-null, then it is called for each element
in the hash. DESTRUCTOR may, if appropriate, deallocate the
memory used by the hash element. However, modifying hash
table H while hash_clear() is running, using any of the
functions hash_clear(), hash_destroy(), hash_insert(),
hash_replace(), or hash_delete(), yields undefined behavior,
whether done in DESTRUCTOR or elsewhere. */
void
hash_clear (struct hash *h, hash_action_func *destructor)
{
size_t i;
for (i = 0; i < h->bucket_cnt; i++)
{
struct list *bucket = &h->buckets[i];
if (destructor != NULL)
while (!list_empty (bucket))
{
struct list_elem *list_elem = list_pop_front (bucket);
struct hash_elem *hash_elem = list_elem_to_hash_elem (list_elem);
destructor (hash_elem, h->aux);
}
list_init (bucket);
}
h->elem_cnt = 0;
}
/* Destroys hash table H.
If DESTRUCTOR is non-null, then it is first called for each
element in the hash. DESTRUCTOR may, if appropriate,
deallocate the memory used by the hash element. However,
modifying hash table H while hash_clear() is running, using
any of the functions hash_clear(), hash_destroy(),
hash_insert(), hash_replace(), or hash_delete(), yields
undefined behavior, whether done in DESTRUCTOR or
elsewhere. */
void
hash_destroy (struct hash *h, hash_action_func *destructor)
{
if (destructor != NULL)
hash_clear (h, destructor);
free (h->buckets);
}
/* Inserts NEW into hash table H and returns a null pointer, if
no equal element is already in the table.
If an equal element is already in the table, returns it
without inserting NEW. */
struct hash_elem *
hash_insert (struct hash *h, struct hash_elem *new)
{
struct list *bucket = find_bucket (h, new);
struct hash_elem *old = find_elem (h, bucket, new);
if (old == NULL)
insert_elem (h, bucket, new);
rehash (h);
return old;
}
/* Inserts NEW into hash table H, replacing any equal element
already in the table, which is returned. */
struct hash_elem *
hash_replace (struct hash *h, struct hash_elem *new)
{
struct list *bucket = find_bucket (h, new);
struct hash_elem *old = find_elem (h, bucket, new);
if (old != NULL)
remove_elem (h, old);
insert_elem (h, bucket, new);
rehash (h);
return old;
}
/* Finds and returns an element equal to E in hash table H, or a
null pointer if no equal element exists in the table. */
struct hash_elem *
hash_find (struct hash *h, struct hash_elem *e)
{
return find_elem (h, find_bucket (h, e), e);
}
/* Finds, removes, and returns an element equal to E in hash
table H. Returns a null pointer if no equal element existed
in the table.
If the elements of the hash table are dynamically allocated,
or own resources that are, then it is the caller's
responsibility to deallocate them. */
struct hash_elem *
hash_delete (struct hash *h, struct hash_elem *e)
{
struct hash_elem *found = find_elem (h, find_bucket (h, e), e);
if (found != NULL)
{
remove_elem (h, found);
rehash (h);
}
return found;
}
/* Calls ACTION for each element in hash table H in arbitrary
order.
Modifying hash table H while hash_apply() is running, using
any of the functions hash_clear(), hash_destroy(),
hash_insert(), hash_replace(), or hash_delete(), yields
undefined behavior, whether done from ACTION or elsewhere. */
void
hash_apply (struct hash *h, hash_action_func *action)
{
size_t i;
ASSERT (action != NULL);
for (i = 0; i < h->bucket_cnt; i++)
{
struct list *bucket = &h->buckets[i];
struct list_elem *elem, *next;
for (elem = list_begin (bucket); elem != list_end (bucket); elem = next)
{
next = list_next (elem);
action (list_elem_to_hash_elem (elem), h->aux);
}
}
}
/* Initializes I for iterating hash table H.
Iteration idiom:
struct hash_iterator i;
hash_first (&i, h);
while (hash_next (&i))
{
struct foo *f = hash_entry (hash_cur (&i), struct foo, elem);
...do something with f...
}
Modifying hash table H during iteration, using any of the
functions hash_clear(), hash_destroy(), hash_insert(),
hash_replace(), or hash_delete(), invalidates all
iterators. */
void
hash_first (struct hash_iterator *i, struct hash *h)
{
ASSERT (i != NULL);
ASSERT (h != NULL);
i->hash = h;
i->bucket = i->hash->buckets;
i->elem = list_elem_to_hash_elem (list_head (i->bucket));
}
/* Advances I to the next element in the hash table and returns
it. Returns a null pointer if no elements are left. Elements
are returned in arbitrary order.
Modifying a hash table H during iteration, using any of the
functions hash_clear(), hash_destroy(), hash_insert(),
hash_replace(), or hash_delete(), invalidates all
iterators. */
struct hash_elem *
hash_next (struct hash_iterator *i)
{
ASSERT (i != NULL);
i->elem = list_elem_to_hash_elem (list_next (&i->elem->list_elem));
while (i->elem == list_elem_to_hash_elem (list_end (i->bucket)))
{
if (++i->bucket >= i->hash->buckets + i->hash->bucket_cnt)
{
i->elem = NULL;
break;
}
i->elem = list_elem_to_hash_elem (list_begin (i->bucket));
}
return i->elem;
}
/* Returns the current element in the hash table iteration, or a
null pointer at the end of the table. Undefined behavior
after calling hash_first() but before hash_next(). */
struct hash_elem *
hash_cur (struct hash_iterator *i)
{
return i->elem;
}
/* Returns the number of elements in H. */
size_t
hash_size (struct hash *h)
{
return h->elem_cnt;
}
/* Returns true if H contains no elements, false otherwise. */
bool
hash_empty (struct hash *h)
{
return h->elem_cnt == 0;
}
/* Fowler-Noll-Vo hash constants, for 32-bit word sizes. */
#define FNV_32_PRIME 16777619u
#define FNV_32_BASIS 2166136261u
/* Returns a hash of the SIZE bytes in BUF. */
unsigned
hash_bytes (const void *buf_, size_t size)
{
/* Fowler-Noll-Vo 32-bit hash, for bytes. */
const unsigned char *buf = buf_;
unsigned hash;
ASSERT (buf != NULL);
hash = FNV_32_BASIS;
while (size-- > 0)
hash = (hash * FNV_32_PRIME) ^ *buf++;
return hash;
}
/* Returns a hash of string S. */
unsigned
hash_string (const char *s_)
{
const unsigned char *s = (const unsigned char *) s_;
unsigned hash;
ASSERT (s != NULL);
hash = FNV_32_BASIS;
while (*s != '\0')
hash = (hash * FNV_32_PRIME) ^ *s++;
return hash;
}
/* Returns a hash of integer I. */
unsigned
hash_int (int i)
{
return hash_bytes (&i, sizeof i);
}
/* Returns the bucket in H that E belongs in. */
static struct list *
find_bucket (struct hash *h, struct hash_elem *e)
{
size_t bucket_idx = h->hash (e, h->aux) & (h->bucket_cnt - 1);
return &h->buckets[bucket_idx];
}
/* Searches BUCKET in H for a hash element equal to E. Returns
it if found or a null pointer otherwise. */
static struct hash_elem *
find_elem (struct hash *h, struct list *bucket, struct hash_elem *e)
{
struct list_elem *i;
for (i = list_begin (bucket); i != list_end (bucket); i = list_next (i))
{
struct hash_elem *hi = list_elem_to_hash_elem (i);
if (!h->less (hi, e, h->aux) && !h->less (e, hi, h->aux))
return hi;
}
return NULL;
}
/* Returns X with its lowest-order bit set to 1 turned off. */
static inline size_t
turn_off_least_1bit (size_t x)
{
return x & (x - 1);
}
/* Returns true if X is a power of 2, otherwise false. */
static inline size_t
is_power_of_2 (size_t x)
{
return x != 0 && turn_off_least_1bit (x) == 0;
}
/* Element per bucket ratios. */
#define MIN_ELEMS_PER_BUCKET 1 /* Elems/bucket < 1: reduce # of buckets. */
#define BEST_ELEMS_PER_BUCKET 2 /* Ideal elems/bucket. */
#define MAX_ELEMS_PER_BUCKET 4 /* Elems/bucket > 4: increase # of buckets. */
/* Changes the number of buckets in hash table H to match the
ideal. This function can fail because of an out-of-memory
condition, but that'll just make hash accesses less efficient;
we can still continue. */
static void
rehash (struct hash *h)
{
size_t old_bucket_cnt, new_bucket_cnt;
struct list *new_buckets, *old_buckets;
size_t i;
ASSERT (h != NULL);
/* Save old bucket info for later use. */
old_buckets = h->buckets;
old_bucket_cnt = h->bucket_cnt;
/* Calculate the number of buckets to use now.
We want one bucket for about every BEST_ELEMS_PER_BUCKET.
We must have at least four buckets, and the number of
buckets must be a power of 2. */
new_bucket_cnt = h->elem_cnt / BEST_ELEMS_PER_BUCKET;
if (new_bucket_cnt < 4)
new_bucket_cnt = 4;
while (!is_power_of_2 (new_bucket_cnt))
new_bucket_cnt = turn_off_least_1bit (new_bucket_cnt);
/* Don't do anything if the bucket count wouldn't change. */
if (new_bucket_cnt == old_bucket_cnt)
return;
/* Allocate new buckets and initialize them as empty. */
new_buckets = malloc (sizeof *new_buckets * new_bucket_cnt);
if (new_buckets == NULL)
{
/* Allocation failed. This means that use of the hash table will
be less efficient. However, it is still usable, so
there's no reason for it to be an error. */
return;
}
for (i = 0; i < new_bucket_cnt; i++)
list_init (&new_buckets[i]);
/* Install new bucket info. */
h->buckets = new_buckets;
h->bucket_cnt = new_bucket_cnt;
/* Move each old element into the appropriate new bucket. */
for (i = 0; i < old_bucket_cnt; i++)
{
struct list *old_bucket;
struct list_elem *elem, *next;
old_bucket = &old_buckets[i];
for (elem = list_begin (old_bucket);
elem != list_end (old_bucket); elem = next)
{
struct list *new_bucket
= find_bucket (h, list_elem_to_hash_elem (elem));
next = list_next (elem);
list_remove (elem);
list_push_front (new_bucket, elem);
}
}
free (old_buckets);
}
/* Inserts E into BUCKET (in hash table H). */
static void
insert_elem (struct hash *h, struct list *bucket, struct hash_elem *e)
{
h->elem_cnt++;
list_push_front (bucket, &e->list_elem);
}
/* Removes E from hash table H. */
static void
remove_elem (struct hash *h, struct hash_elem *e)
{
h->elem_cnt--;
list_remove (&e->list_elem);
}
| 10cm | trunk/10cm/pintos/src/lib/kernel/hash.c | C | oos | 11,718 |
#include <console.h>
#include <stdarg.h>
#include <stdio.h>
#include "devices/serial.h"
#include "devices/vga.h"
#include "threads/init.h"
#include "threads/interrupt.h"
#include "threads/synch.h"
static void vprintf_helper (char, void *);
static void putchar_have_lock (uint8_t c);
/* The console lock.
Both the vga and serial layers do their own locking, so it's
safe to call them at any time.
But this lock is useful to prevent simultaneous printf() calls
from mixing their output, which looks confusing. */
static struct lock console_lock;
/* True in ordinary circumstances: we want to use the console
lock to avoid mixing output between threads, as explained
above.
False in early boot before the point that locks are functional
or the console lock has been initialized, or after a kernel
panics. In the former case, taking the lock would cause an
assertion failure, which in turn would cause a panic, turning
it into the latter case. In the latter case, if it is a buggy
lock_acquire() implementation that caused the panic, we'll
likely just recurse. */
static bool use_console_lock;
/* It's possible, if you add enough debug output to Pintos, to
try to recursively grab console_lock from a single thread. As
a real example, I added a printf() call to palloc_free().
Here's a real backtrace that resulted:
lock_console()
vprintf()
printf() - palloc() tries to grab the lock again
palloc_free()
schedule_tail() - another thread dying as we switch threads
schedule()
thread_yield()
intr_handler() - timer interrupt
intr_set_level()
serial_putc()
putchar_have_lock()
putbuf()
sys_write() - one process writing to the console
syscall_handler()
intr_handler()
This kind of thing is very difficult to debug, so we avoid the
problem by simulating a recursive lock with a depth
counter. */
static int console_lock_depth;
/* Number of characters written to console. */
static int64_t write_cnt;
/* Enable console locking. */
void
console_init (void)
{
lock_init (&console_lock);
use_console_lock = true;
}
/* Notifies the console that a kernel panic is underway,
which warns it to avoid trying to take the console lock from
now on. */
void
console_panic (void)
{
use_console_lock = false;
}
/* Prints console statistics. */
void
console_print_stats (void)
{
printf ("Console: %lld characters output\n", write_cnt);
}
/* Acquires the console lock. */
static void
acquire_console (void)
{
if (!intr_context () && use_console_lock)
{
if (lock_held_by_current_thread (&console_lock))
console_lock_depth++;
else
lock_acquire (&console_lock);
}
}
/* Releases the console lock. */
static void
release_console (void)
{
if (!intr_context () && use_console_lock)
{
if (console_lock_depth > 0)
console_lock_depth--;
else
lock_release (&console_lock);
}
}
/* Returns true if the current thread has the console lock,
false otherwise. */
static bool
console_locked_by_current_thread (void)
{
return (intr_context ()
|| !use_console_lock
|| lock_held_by_current_thread (&console_lock));
}
/* The standard vprintf() function,
which is like printf() but uses a va_list.
Writes its output to both vga display and serial port. */
int
vprintf (const char *format, va_list args)
{
int char_cnt = 0;
acquire_console ();
__vprintf (format, args, vprintf_helper, &char_cnt);
release_console ();
return char_cnt;
}
/* Writes string S to the console, followed by a new-line
character. */
int
puts (const char *s)
{
acquire_console ();
while (*s != '\0')
putchar_have_lock (*s++);
putchar_have_lock ('\n');
release_console ();
return 0;
}
/* Writes the N characters in BUFFER to the console. */
void
putbuf (const char *buffer, size_t n)
{
acquire_console ();
while (n-- > 0)
putchar_have_lock (*buffer++);
release_console ();
}
/* Writes C to the vga display and serial port. */
int
putchar (int c)
{
acquire_console ();
putchar_have_lock (c);
release_console ();
return c;
}
/* Helper function for vprintf(). */
static void
vprintf_helper (char c, void *char_cnt_)
{
int *char_cnt = char_cnt_;
(*char_cnt)++;
putchar_have_lock (c);
}
/* Writes C to the vga display and serial port.
The caller has already acquired the console lock if
appropriate. */
static void
putchar_have_lock (uint8_t c)
{
ASSERT (console_locked_by_current_thread ());
write_cnt++;
serial_putc (c);
vga_putc (c);
}
| 10cm | trunk/10cm/pintos/src/lib/kernel/console.c | C | oos | 4,634 |
#include "list.h"
#include "../debug.h"
/* Our doubly linked lists have two header elements: the "head"
just before the first element and the "tail" just after the
last element. The `prev' link of the front header is null, as
is the `next' link of the back header. Their other two links
point toward each other via the interior elements of the list.
An empty list looks like this:
+------+ +------+
<---| head |<--->| tail |--->
+------+ +------+
A list with two elements in it looks like this:
+------+ +-------+ +-------+ +------+
<---| head |<--->| 1 |<--->| 2 |<--->| tail |<--->
+------+ +-------+ +-------+ +------+
The symmetry of this arrangement eliminates lots of special
cases in list processing. For example, take a look at
list_remove(): it takes only two pointer assignments and no
conditionals. That's a lot simpler than the code would be
without header elements.
(Because only one of the pointers in each header element is used,
we could in fact combine them into a single header element
without sacrificing this simplicity. But using two separate
elements allows us to do a little bit of checking on some
operations, which can be valuable.) */
static bool is_sorted (struct list_elem *a, struct list_elem *b,
list_less_func *less, void *aux) UNUSED;
/* Returns true if ELEM is a head, false otherwise. */
static inline bool
is_head (struct list_elem *elem)
{
return elem != NULL && elem->prev == NULL && elem->next != NULL;
}
/* Returns true if ELEM is an interior element,
false otherwise. */
static inline bool
is_interior (struct list_elem *elem)
{
return elem != NULL && elem->prev != NULL && elem->next != NULL;
}
/* Returns true if ELEM is a tail, false otherwise. */
static inline bool
is_tail (struct list_elem *elem)
{
return elem != NULL && elem->prev != NULL && elem->next == NULL;
}
/* Initializes LIST as an empty list. */
void
list_init (struct list *list)
{
ASSERT (list != NULL);
list->head.prev = NULL;
list->head.next = &list->tail;
list->tail.prev = &list->head;
list->tail.next = NULL;
}
/* Returns the beginning of LIST. */
struct list_elem *
list_begin (struct list *list)
{
ASSERT (list != NULL);
return list->head.next;
}
/* Returns the element after ELEM in its list. If ELEM is the
last element in its list, returns the list tail. Results are
undefined if ELEM is itself a list tail. */
struct list_elem *
list_next (struct list_elem *elem)
{
ASSERT (is_head (elem) || is_interior (elem));
return elem->next;
}
/* Returns LIST's tail.
list_end() is often used in iterating through a list from
front to back. See the big comment at the top of list.h for
an example. */
struct list_elem *
list_end (struct list *list)
{
ASSERT (list != NULL);
return &list->tail;
}
/* Returns the LIST's reverse beginning, for iterating through
LIST in reverse order, from back to front. */
struct list_elem *
list_rbegin (struct list *list)
{
ASSERT (list != NULL);
return list->tail.prev;
}
/* Returns the element before ELEM in its list. If ELEM is the
first element in its list, returns the list head. Results are
undefined if ELEM is itself a list head. */
struct list_elem *
list_prev (struct list_elem *elem)
{
ASSERT (is_interior (elem) || is_tail (elem));
return elem->prev;
}
/* Returns LIST's head.
list_rend() is often used in iterating through a list in
reverse order, from back to front. Here's typical usage,
following the example from the top of list.h:
for (e = list_rbegin (&foo_list); e != list_rend (&foo_list);
e = list_prev (e))
{
struct foo *f = list_entry (e, struct foo, elem);
...do something with f...
}
*/
struct list_elem *
list_rend (struct list *list)
{
ASSERT (list != NULL);
return &list->head;
}
/* Return's LIST's head.
list_head() can be used for an alternate style of iterating
through a list, e.g.:
e = list_head (&list);
while ((e = list_next (e)) != list_end (&list))
{
...
}
*/
struct list_elem *
list_head (struct list *list)
{
ASSERT (list != NULL);
return &list->head;
}
/* Return's LIST's tail. */
struct list_elem *
list_tail (struct list *list)
{
ASSERT (list != NULL);
return &list->tail;
}
/* Inserts ELEM just before BEFORE, which may be either an
interior element or a tail. The latter case is equivalent to
list_push_back(). */
void
list_insert (struct list_elem *before, struct list_elem *elem)
{
ASSERT (is_interior (before) || is_tail (before));
ASSERT (elem != NULL);
elem->prev = before->prev;
elem->next = before;
before->prev->next = elem;
before->prev = elem;
}
/* Removes elements FIRST though LAST (exclusive) from their
current list, then inserts them just before BEFORE, which may
be either an interior element or a tail. */
void
list_splice (struct list_elem *before,
struct list_elem *first, struct list_elem *last)
{
ASSERT (is_interior (before) || is_tail (before));
if (first == last)
return;
last = list_prev (last);
ASSERT (is_interior (first));
ASSERT (is_interior (last));
/* Cleanly remove FIRST...LAST from its current list. */
first->prev->next = last->next;
last->next->prev = first->prev;
/* Splice FIRST...LAST into new list. */
first->prev = before->prev;
last->next = before;
before->prev->next = first;
before->prev = last;
}
/* Inserts ELEM at the beginning of LIST, so that it becomes the
front in LIST. */
void
list_push_front (struct list *list, struct list_elem *elem)
{
list_insert (list_begin (list), elem);
}
/* Inserts ELEM at the end of LIST, so that it becomes the
back in LIST. */
void
list_push_back (struct list *list, struct list_elem *elem)
{
list_insert (list_end (list), elem);
}
/* Removes ELEM from its list and returns the element that
followed it. Undefined behavior if ELEM is not in a list.
It's not safe to treat ELEM as an element in a list after
removing it. In particular, using list_next() or list_prev()
on ELEM after removal yields undefined behavior. This means
that a naive loop to remove the elements in a list will fail:
** DON'T DO THIS **
for (e = list_begin (&list); e != list_end (&list); e = list_next (e))
{
...do something with e...
list_remove (e);
}
** DON'T DO THIS **
Here is one correct way to iterate and remove elements from a
list:
for (e = list_begin (&list); e != list_end (&list); e = list_remove (e))
{
...do something with e...
}
If you need to free() elements of the list then you need to be
more conservative. Here's an alternate strategy that works
even in that case:
while (!list_empty (&list))
{
struct list_elem *e = list_pop_front (&list);
...do something with e...
}
*/
struct list_elem *
list_remove (struct list_elem *elem)
{
ASSERT (is_interior (elem));
elem->prev->next = elem->next;
elem->next->prev = elem->prev;
return elem->next;
}
/* Removes the front element from LIST and returns it.
Undefined behavior if LIST is empty before removal. */
struct list_elem *
list_pop_front (struct list *list)
{
struct list_elem *front = list_front (list);
list_remove (front);
return front;
}
/* Removes the back element from LIST and returns it.
Undefined behavior if LIST is empty before removal. */
struct list_elem *
list_pop_back (struct list *list)
{
struct list_elem *back = list_back (list);
list_remove (back);
return back;
}
/* Returns the front element in LIST.
Undefined behavior if LIST is empty. */
struct list_elem *
list_front (struct list *list)
{
ASSERT (!list_empty (list));
return list->head.next;
}
/* Returns the back element in LIST.
Undefined behavior if LIST is empty. */
struct list_elem *
list_back (struct list *list)
{
ASSERT (!list_empty (list));
return list->tail.prev;
}
/* Returns the number of elements in LIST.
Runs in O(n) in the number of elements. */
size_t
list_size (struct list *list)
{
struct list_elem *e;
size_t cnt = 0;
for (e = list_begin (list); e != list_end (list); e = list_next (e))
cnt++;
return cnt;
}
/* Returns true if LIST is empty, false otherwise. */
bool
list_empty (struct list *list)
{
return list_begin (list) == list_end (list);
}
/* Swaps the `struct list_elem *'s that A and B point to. */
static void
swap (struct list_elem **a, struct list_elem **b)
{
struct list_elem *t = *a;
*a = *b;
*b = t;
}
/* Reverses the order of LIST. */
void
list_reverse (struct list *list)
{
if (!list_empty (list))
{
struct list_elem *e;
for (e = list_begin (list); e != list_end (list); e = e->prev)
swap (&e->prev, &e->next);
swap (&list->head.next, &list->tail.prev);
swap (&list->head.next->prev, &list->tail.prev->next);
}
}
/* Returns true only if the list elements A through B (exclusive)
are in order according to LESS given auxiliary data AUX. */
static bool
is_sorted (struct list_elem *a, struct list_elem *b,
list_less_func *less, void *aux)
{
if (a != b)
while ((a = list_next (a)) != b)
if (less (a, list_prev (a), aux))
return false;
return true;
}
/* Finds a run, starting at A and ending not after B, of list
elements that are in nondecreasing order according to LESS
given auxiliary data AUX. Returns the (exclusive) end of the
run.
A through B (exclusive) must form a non-empty range. */
static struct list_elem *
find_end_of_run (struct list_elem *a, struct list_elem *b,
list_less_func *less, void *aux)
{
ASSERT (a != NULL);
ASSERT (b != NULL);
ASSERT (less != NULL);
ASSERT (a != b);
do
{
a = list_next (a);
}
while (a != b && !less (a, list_prev (a), aux));
return a;
}
/* Merges A0 through A1B0 (exclusive) with A1B0 through B1
(exclusive) to form a combined range also ending at B1
(exclusive). Both input ranges must be nonempty and sorted in
nondecreasing order according to LESS given auxiliary data
AUX. The output range will be sorted the same way. */
static void
inplace_merge (struct list_elem *a0, struct list_elem *a1b0,
struct list_elem *b1,
list_less_func *less, void *aux)
{
ASSERT (a0 != NULL);
ASSERT (a1b0 != NULL);
ASSERT (b1 != NULL);
ASSERT (less != NULL);
ASSERT (is_sorted (a0, a1b0, less, aux));
ASSERT (is_sorted (a1b0, b1, less, aux));
while (a0 != a1b0 && a1b0 != b1)
if (!less (a1b0, a0, aux))
a0 = list_next (a0);
else
{
a1b0 = list_next (a1b0);
list_splice (a0, list_prev (a1b0), a1b0);
}
}
/* Sorts LIST according to LESS given auxiliary data AUX, using a
natural iterative merge sort that runs in O(n lg n) time and
O(1) space in the number of elements in LIST. */
void
list_sort (struct list *list, list_less_func *less, void *aux)
{
size_t output_run_cnt; /* Number of runs output in current pass. */
ASSERT (list != NULL);
ASSERT (less != NULL);
/* Pass over the list repeatedly, merging adjacent runs of
nondecreasing elements, until only one run is left. */
do
{
struct list_elem *a0; /* Start of first run. */
struct list_elem *a1b0; /* End of first run, start of second. */
struct list_elem *b1; /* End of second run. */
output_run_cnt = 0;
for (a0 = list_begin (list); a0 != list_end (list); a0 = b1)
{
/* Each iteration produces one output run. */
output_run_cnt++;
/* Locate two adjacent runs of nondecreasing elements
A0...A1B0 and A1B0...B1. */
a1b0 = find_end_of_run (a0, list_end (list), less, aux);
if (a1b0 == list_end (list))
break;
b1 = find_end_of_run (a1b0, list_end (list), less, aux);
/* Merge the runs. */
inplace_merge (a0, a1b0, b1, less, aux);
}
}
while (output_run_cnt > 1);
ASSERT (is_sorted (list_begin (list), list_end (list), less, aux));
}
/* Inserts ELEM in the proper position in LIST, which must be
sorted according to LESS given auxiliary data AUX.
Runs in O(n) average case in the number of elements in LIST. */
void
list_insert_ordered (struct list *list, struct list_elem *elem,
list_less_func *less, void *aux)
{
struct list_elem *e;
ASSERT (list != NULL);
ASSERT (elem != NULL);
ASSERT (less != NULL);
for (e = list_begin (list); e != list_end (list); e = list_next (e))
if (less (elem, e, aux))
break;
return list_insert (e, elem);
}
/* Iterates through LIST and removes all but the first in each
set of adjacent elements that are equal according to LESS
given auxiliary data AUX. If DUPLICATES is non-null, then the
elements from LIST are appended to DUPLICATES. */
void
list_unique (struct list *list, struct list *duplicates,
list_less_func *less, void *aux)
{
struct list_elem *elem, *next;
ASSERT (list != NULL);
ASSERT (less != NULL);
if (list_empty (list))
return;
elem = list_begin (list);
while ((next = list_next (elem)) != list_end (list))
if (!less (elem, next, aux) && !less (next, elem, aux))
{
list_remove (next);
if (duplicates != NULL)
list_push_back (duplicates, next);
}
else
elem = next;
}
/* Returns the element in LIST with the largest value according
to LESS given auxiliary data AUX. If there is more than one
maximum, returns the one that appears earlier in the list. If
the list is empty, returns its tail. */
struct list_elem *
list_max (struct list *list, list_less_func *less, void *aux)
{
struct list_elem *max = list_begin (list);
if (max != list_end (list))
{
struct list_elem *e;
for (e = list_next (max); e != list_end (list); e = list_next (e))
if (less (max, e, aux))
max = e;
}
return max;
}
/* Returns the element in LIST with the smallest value according
to LESS given auxiliary data AUX. If there is more than one
minimum, returns the one that appears earlier in the list. If
the list is empty, returns its tail. */
struct list_elem *
list_min (struct list *list, list_less_func *less, void *aux)
{
struct list_elem *min = list_begin (list);
if (min != list_end (list))
{
struct list_elem *e;
for (e = list_next (min); e != list_end (list); e = list_next (e))
if (less (e, min, aux))
min = e;
}
return min;
}
// list에서 다음 원소를 return. 현재 list_elem *e 가 list의 마지막 원소를 가리키고 있다면
// list의 가장 처음 원소를 return 한다.
struct list_elem * list_clock_next(struct list_elem *e, struct list *l)
{
// list에서 clock처럼 돌면서 다음 frame을 가리키도록 한다.
return (list_next(e) == list_end(l)) ? list_front(l) : list_next(e);
}
| 10cm | trunk/10cm/pintos/src/lib/kernel/list.c | C | oos | 15,175 |
#include <debug.h>
#include <console.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include "threads/init.h"
#include "threads/interrupt.h"
#include "threads/thread.h"
#include "threads/switch.h"
#include "threads/vaddr.h"
#include "devices/serial.h"
/* Halts the OS, printing the source file name, line number, and
function name, plus a user-specific message. */
void
debug_panic (const char *file, int line, const char *function,
const char *message, ...)
{
static int level;
va_list args;
intr_disable ();
console_panic ();
level++;
if (level == 1)
{
printf ("Kernel PANIC at %s:%d in %s(): ", file, line, function);
va_start (args, message);
vprintf (message, args);
printf ("\n");
va_end (args);
debug_backtrace ();
}
else if (level == 2)
printf ("Kernel PANIC recursion at %s:%d in %s().\n",
file, line, function);
else
{
/* Don't print anything: that's probably why we recursed. */
}
serial_flush ();
if (power_off_when_done)
power_off ();
for (;;);
}
/* Print call stack of a thread.
The thread may be running, ready, or blocked. */
static void
print_stacktrace(struct thread *t, void *aux UNUSED)
{
void *retaddr = NULL, **frame = NULL;
const char *status = "UNKNOWN";
switch (t->status) {
case THREAD_RUNNING:
status = "RUNNING";
break;
case THREAD_READY:
status = "READY";
break;
case THREAD_BLOCKED:
status = "BLOCKED";
break;
default:
break;
}
printf ("Call stack of thread `%s' (status %s):", t->name, status);
if (t == thread_current())
{
frame = __builtin_frame_address (1);
retaddr = __builtin_return_address (0);
}
else
{
/* Retrieve the values of the base and instruction pointers
as they were saved when this thread called switch_threads. */
struct switch_threads_frame * saved_frame;
saved_frame = (struct switch_threads_frame *)t->stack;
/* Skip threads if they have been added to the all threads
list, but have never been scheduled.
We can identify because their `stack' member either points
at the top of their kernel stack page, or the
switch_threads_frame's 'eip' member points at switch_entry.
See also threads.c. */
if (t->stack == (uint8_t *)t + PGSIZE || saved_frame->eip == switch_entry)
{
printf (" thread was never scheduled.\n");
return;
}
frame = (void **) saved_frame->ebp;
retaddr = (void *) saved_frame->eip;
}
printf (" %p", retaddr);
for (; (uintptr_t) frame >= 0x1000 && frame[0] != NULL; frame = frame[0])
printf (" %p", frame[1]);
printf (".\n");
}
/* Prints call stack of all threads. */
void
debug_backtrace_all (void)
{
enum intr_level oldlevel = intr_disable ();
thread_foreach (print_stacktrace, 0);
intr_set_level (oldlevel);
}
| 10cm | trunk/10cm/pintos/src/lib/kernel/debug.c | C | oos | 3,031 |
#include "bitmap.h"
#include <debug.h>
#include <limits.h>
#include <round.h>
#include <stdio.h>
#include "threads/malloc.h"
#ifdef FILESYS
#include "filesys/file.h"
#endif
/* Element type.
This must be an unsigned integer type at least as wide as int.
Each bit represents one bit in the bitmap.
If bit 0 in an element represents bit K in the bitmap,
then bit 1 in the element represents bit K+1 in the bitmap,
and so on. */
typedef unsigned long elem_type;
/* Number of bits in an element. */
#define ELEM_BITS (sizeof (elem_type) * CHAR_BIT)
/* From the outside, a bitmap is an array of bits. From the
inside, it's an array of elem_type (defined above) that
simulates an array of bits. */
struct bitmap
{
size_t bit_cnt; /* Number of bits. */
elem_type *bits; /* Elements that represent bits. */
};
/* Returns the index of the element that contains the bit
numbered BIT_IDX. */
static inline size_t
elem_idx (size_t bit_idx)
{
return bit_idx / ELEM_BITS;
}
/* Returns an elem_type where only the bit corresponding to
BIT_IDX is turned on. */
static inline elem_type
bit_mask (size_t bit_idx)
{
return (elem_type) 1 << (bit_idx % ELEM_BITS);
}
/* Returns the number of elements required for BIT_CNT bits. */
static inline size_t
elem_cnt (size_t bit_cnt)
{
return DIV_ROUND_UP (bit_cnt, ELEM_BITS);
}
/* Returns the number of bytes required for BIT_CNT bits. */
static inline size_t
byte_cnt (size_t bit_cnt)
{
return sizeof (elem_type) * elem_cnt (bit_cnt);
}
/* Returns a bit mask in which the bits actually used in the last
element of B's bits are set to 1 and the rest are set to 0. */
static inline elem_type
last_mask (const struct bitmap *b)
{
int last_bits = b->bit_cnt % ELEM_BITS;
return last_bits ? ((elem_type) 1 << last_bits) - 1 : (elem_type) -1;
}
/* Creation and destruction. */
/* Initializes B to be a bitmap of BIT_CNT bits
and sets all of its bits to false.
Returns true if success, false if memory allocation
failed. */
struct bitmap *
bitmap_create (size_t bit_cnt)
{
struct bitmap *b = malloc (sizeof *b);
if (b != NULL)
{
b->bit_cnt = bit_cnt;
b->bits = malloc (byte_cnt (bit_cnt));
if (b->bits != NULL || bit_cnt == 0)
{
bitmap_set_all (b, false);
return b;
}
free (b);
}
return NULL;
}
/* Creates and returns a bitmap with BIT_CNT bits in the
BLOCK_SIZE bytes of storage preallocated at BLOCK.
BLOCK_SIZE must be at least bitmap_needed_bytes(BIT_CNT). */
struct bitmap *
bitmap_create_in_buf (size_t bit_cnt, void *block, size_t block_size UNUSED)
{
struct bitmap *b = block;
ASSERT (block_size >= bitmap_buf_size (bit_cnt));
b->bit_cnt = bit_cnt;
b->bits = (elem_type *) (b + 1);
bitmap_set_all (b, false);
return b;
}
/* Returns the number of bytes required to accomodate a bitmap
with BIT_CNT bits (for use with bitmap_create_in_buf()). */
size_t
bitmap_buf_size (size_t bit_cnt)
{
return sizeof (struct bitmap) + byte_cnt (bit_cnt);
}
/* Destroys bitmap B, freeing its storage.
Not for use on bitmaps created by
bitmap_create_preallocated(). */
void
bitmap_destroy (struct bitmap *b)
{
if (b != NULL)
{
free (b->bits);
free (b);
}
}
/* Bitmap size. */
/* Returns the number of bits in B. */
size_t
bitmap_size (const struct bitmap *b)
{
return b->bit_cnt;
}
/* Setting and testing single bits. */
/* Atomically sets the bit numbered IDX in B to VALUE. */
void
bitmap_set (struct bitmap *b, size_t idx, bool value)
{
ASSERT (b != NULL);
ASSERT (idx < b->bit_cnt);
if (value)
bitmap_mark (b, idx);
else
bitmap_reset (b, idx);
}
/* Atomically sets the bit numbered BIT_IDX in B to true. */
void
bitmap_mark (struct bitmap *b, size_t bit_idx)
{
size_t idx = elem_idx (bit_idx);
elem_type mask = bit_mask (bit_idx);
/* This is equivalent to `b->bits[idx] |= mask' except that it
is guaranteed to be atomic on a uniprocessor machine. See
the description of the OR instruction in [IA32-v2b]. */
asm ("orl %1, %0" : "=m" (b->bits[idx]) : "r" (mask) : "cc");
}
/* Atomically sets the bit numbered BIT_IDX in B to false. */
void
bitmap_reset (struct bitmap *b, size_t bit_idx)
{
size_t idx = elem_idx (bit_idx);
elem_type mask = bit_mask (bit_idx);
/* This is equivalent to `b->bits[idx] &= ~mask' except that it
is guaranteed to be atomic on a uniprocessor machine. See
the description of the AND instruction in [IA32-v2a]. */
asm ("andl %1, %0" : "=m" (b->bits[idx]) : "r" (~mask) : "cc");
}
/* Atomically toggles the bit numbered IDX in B;
that is, if it is true, makes it false,
and if it is false, makes it true. */
void
bitmap_flip (struct bitmap *b, size_t bit_idx)
{
size_t idx = elem_idx (bit_idx);
elem_type mask = bit_mask (bit_idx);
/* This is equivalent to `b->bits[idx] ^= mask' except that it
is guaranteed to be atomic on a uniprocessor machine. See
the description of the XOR instruction in [IA32-v2b]. */
asm ("xorl %1, %0" : "=m" (b->bits[idx]) : "r" (mask) : "cc");
}
/* Returns the value of the bit numbered IDX in B. */
bool
bitmap_test (const struct bitmap *b, size_t idx)
{
ASSERT (b != NULL);
ASSERT (idx < b->bit_cnt);
return (b->bits[elem_idx (idx)] & bit_mask (idx)) != 0;
}
/* Setting and testing multiple bits. */
/* Sets all bits in B to VALUE. */
void
bitmap_set_all (struct bitmap *b, bool value)
{
ASSERT (b != NULL);
bitmap_set_multiple (b, 0, bitmap_size (b), value);
}
/* Sets the CNT bits starting at START in B to VALUE. */
void
bitmap_set_multiple (struct bitmap *b, size_t start, size_t cnt, bool value)
{
size_t i;
ASSERT (b != NULL);
ASSERT (start <= b->bit_cnt);
ASSERT (start + cnt <= b->bit_cnt);
for (i = 0; i < cnt; i++)
bitmap_set (b, start + i, value);
}
/* Returns the number of bits in B between START and START + CNT,
exclusive, that are set to VALUE. */
size_t
bitmap_count (const struct bitmap *b, size_t start, size_t cnt, bool value)
{
size_t i, value_cnt;
ASSERT (b != NULL);
ASSERT (start <= b->bit_cnt);
ASSERT (start + cnt <= b->bit_cnt);
value_cnt = 0;
for (i = 0; i < cnt; i++)
if (bitmap_test (b, start + i) == value)
value_cnt++;
return value_cnt;
}
/* Returns true if any bits in B between START and START + CNT,
exclusive, are set to VALUE, and false otherwise. */
bool
bitmap_contains (const struct bitmap *b, size_t start, size_t cnt, bool value)
{
size_t i;
ASSERT (b != NULL);
ASSERT (start <= b->bit_cnt);
ASSERT (start + cnt <= b->bit_cnt);
for (i = 0; i < cnt; i++)
if (bitmap_test (b, start + i) == value)
return true;
return false;
}
/* Returns true if any bits in B between START and START + CNT,
exclusive, are set to true, and false otherwise.*/
bool
bitmap_any (const struct bitmap *b, size_t start, size_t cnt)
{
return bitmap_contains (b, start, cnt, true);
}
/* Returns true if no bits in B between START and START + CNT,
exclusive, are set to true, and false otherwise.*/
bool
bitmap_none (const struct bitmap *b, size_t start, size_t cnt)
{
return !bitmap_contains (b, start, cnt, true);
}
/* Returns true if every bit in B between START and START + CNT,
exclusive, is set to true, and false otherwise. */
bool
bitmap_all (const struct bitmap *b, size_t start, size_t cnt)
{
return !bitmap_contains (b, start, cnt, false);
}
/* Finding set or unset bits. */
/* Finds and returns the starting index of the first group of CNT
consecutive bits in B at or after START that are all set to
VALUE.
If there is no such group, returns BITMAP_ERROR. */
size_t
bitmap_scan (const struct bitmap *b, size_t start, size_t cnt, bool value)
{
ASSERT (b != NULL);
ASSERT (start <= b->bit_cnt);
if (cnt <= b->bit_cnt)
{
size_t last = b->bit_cnt - cnt;
size_t i;
for (i = start; i <= last; i++)
if (!bitmap_contains (b, i, cnt, !value))
return i;
}
return BITMAP_ERROR;
}
/* Finds the first group of CNT consecutive bits in B at or after
START that are all set to VALUE, flips them all to !VALUE,
and returns the index of the first bit in the group.
If there is no such group, returns BITMAP_ERROR.
If CNT is zero, returns 0.
Bits are set atomically, but testing bits is not atomic with
setting them. */
size_t
bitmap_scan_and_flip (struct bitmap *b, size_t start, size_t cnt, bool value)
{
size_t idx = bitmap_scan (b, start, cnt, value);
if (idx != BITMAP_ERROR)
bitmap_set_multiple (b, idx, cnt, !value);
return idx;
}
/* File input and output. */
#ifdef FILESYS
/* Returns the number of bytes needed to store B in a file. */
size_t
bitmap_file_size (const struct bitmap *b)
{
return byte_cnt (b->bit_cnt);
}
/* Reads B from FILE. Returns true if successful, false
otherwise. */
bool
bitmap_read (struct bitmap *b, struct file *file)
{
bool success = true;
if (b->bit_cnt > 0)
{
off_t size = byte_cnt (b->bit_cnt);
success = file_read_at (file, b->bits, size, 0) == size;
b->bits[elem_cnt (b->bit_cnt) - 1] &= last_mask (b);
}
return success;
}
/* Writes B to FILE. Return true if successful, false
otherwise. */
bool
bitmap_write (const struct bitmap *b, struct file *file)
{
off_t size = byte_cnt (b->bit_cnt);
return file_write_at (file, b->bits, size, 0) == size;
}
#endif /* FILESYS */
/* Debugging. */
/* Dumps the contents of B to the console as hexadecimal. */
void
bitmap_dump (const struct bitmap *b)
{
hex_dump (0, b->bits, byte_cnt (b->bit_cnt), false);
}
| 10cm | trunk/10cm/pintos/src/lib/kernel/bitmap.c | C | oos | 9,658 |
#ifndef __LIB_KERNEL_CONSOLE_H
#define __LIB_KERNEL_CONSOLE_H
void console_init (void);
void console_panic (void);
void console_print_stats (void);
#endif /* lib/kernel/console.h */
| 10cm | trunk/10cm/pintos/src/lib/kernel/console.h | C | oos | 184 |
#ifndef __LIB_DEBUG_H
#define __LIB_DEBUG_H
/* GCC lets us add "attributes" to functions, function
parameters, etc. to indicate their properties.
See the GCC manual for details. */
#define UNUSED __attribute__ ((unused))
#define NO_RETURN __attribute__ ((noreturn))
#define NO_INLINE __attribute__ ((noinline))
#define PRINTF_FORMAT(FMT, FIRST) __attribute__ ((format (printf, FMT, FIRST)))
/* Halts the OS, printing the source file name, line number, and
function name, plus a user-specific message. */
#define PANIC(...) debug_panic (__FILE__, __LINE__, __func__, __VA_ARGS__)
void debug_panic (const char *file, int line, const char *function,
const char *message, ...) PRINTF_FORMAT (4, 5) NO_RETURN;
void debug_backtrace (void);
void debug_backtrace_all (void);
#endif
/* This is outside the header guard so that debug.h may be
included multiple times with different settings of NDEBUG. */
#undef ASSERT
#undef NOT_REACHED
#ifndef NDEBUG
#define ASSERT(CONDITION) \
if (CONDITION) { } else { \
PANIC ("assertion `%s' failed.", #CONDITION); \
}
#define NOT_REACHED() PANIC ("executed an unreachable statement");
#else
#define ASSERT(CONDITION) ((void) 0)
#define NOT_REACHED() for (;;)
#endif /* lib/debug.h */
| 10cm | trunk/10cm/pintos/src/lib/debug.h | C | oos | 1,355 |
#ifndef __LIB_STDARG_H
#define __LIB_STDARG_H
/* GCC has <stdarg.h> functionality as built-ins,
so all we need is to use it. */
typedef __builtin_va_list va_list;
#define va_start(LIST, ARG) __builtin_va_start (LIST, ARG)
#define va_end(LIST) __builtin_va_end (LIST)
#define va_arg(LIST, TYPE) __builtin_va_arg (LIST, TYPE)
#define va_copy(DST, SRC) __builtin_va_copy (DST, SRC)
#endif /* lib/stdarg.h */
| 10cm | trunk/10cm/pintos/src/lib/stdarg.h | C | oos | 423 |
#ifndef __LIB_STDBOOL_H
#define __LIB_STDBOOL_H
#define bool _Bool
#define true 1
#define false 0
#define __bool_true_false_are_defined 1
#endif /* lib/stdbool.h */
| 10cm | trunk/10cm/pintos/src/lib/stdbool.h | C | oos | 167 |
#ifndef __LIB_PACKED_H
#define __LIB_PACKED_H
/* The "packed" attribute, when applied to a structure, prevents
GCC from inserting padding bytes between or after structure
members. It must be specified at the time of the structure's
definition, normally just after the closing brace. */
#define PACKED __attribute__ ((packed))
#endif /* lib/packed.h */
| 10cm | trunk/10cm/pintos/src/lib/packed.h | C | oos | 364 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Blog.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Blog.Tests")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7f7b7207-6092-4d5a-a056-65efe419a970")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 101110blog | trunk/Blog.Tests/Properties/AssemblyInfo.cs | C# | mit | 1,391 |
@{
Layout = "~/Views/Shared/_Layout.cshtml";
} | 101110blog | trunk/Blog/Views/_ViewStart.cshtml | HTML+Razor | mit | 55 |
@model Blog.Models.RegisterModel
@{
ViewBag.Title = "Register";
}
<h2>Create a New Account</h2>
<p>
Use the form below to create a new account.
</p>
<p>
Passwords are required to be a minimum of @Membership.MinRequiredPasswordLength characters in length.
</p>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.")
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
@Html.LabelFor(m => m.UserName)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.UserName)
@Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.Email)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.Email)
@Html.ValidationMessageFor(m => m.Email)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.Password)
</div>
<div class="editor-field">
@Html.PasswordFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.ConfirmPassword)
</div>
<div class="editor-field">
@Html.PasswordFor(m => m.ConfirmPassword)
@Html.ValidationMessageFor(m => m.ConfirmPassword)
</div>
<p>
<input type="submit" value="Register" />
</p>
</fieldset>
</div>
}
| 101110blog | trunk/Blog/Views/Account/Register.cshtml | HTML+Razor | mit | 2,002 |
@model Blog.Models.LogOnModel
@{
ViewBag.Title = "Log On";
}
<h2>Log On</h2>
<p>
Please enter your user name and password. @Html.ActionLink("Register", "Register") if you don't have an account.
</p>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
@using (Html.BeginForm()) {
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
@Html.LabelFor(m => m.UserName)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.UserName)
@Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.Password)
</div>
<div class="editor-field">
@Html.PasswordFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password)
</div>
<div class="editor-label">
@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe)
</div>
<p>
<input type="submit" value="Log On" />
</p>
</fieldset>
</div>
}
| 101110blog | trunk/Blog/Views/Account/LogOn.cshtml | HTML+Razor | mit | 1,506 |
@model Blog.Models.ChangePasswordModel
@{
ViewBag.Title = "Change Password";
}
<h2>Change Password</h2>
<p>
Use the form below to change your password.
</p>
<p>
New passwords are required to be a minimum of @Membership.MinRequiredPasswordLength characters in length.
</p>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true, "Password change was unsuccessful. Please correct the errors and try again.")
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
@Html.LabelFor(m => m.OldPassword)
</div>
<div class="editor-field">
@Html.PasswordFor(m => m.OldPassword)
@Html.ValidationMessageFor(m => m.OldPassword)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.NewPassword)
</div>
<div class="editor-field">
@Html.PasswordFor(m => m.NewPassword)
@Html.ValidationMessageFor(m => m.NewPassword)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.ConfirmPassword)
</div>
<div class="editor-field">
@Html.PasswordFor(m => m.ConfirmPassword)
@Html.ValidationMessageFor(m => m.ConfirmPassword)
</div>
<p>
<input type="submit" value="Change Password" />
</p>
</fieldset>
</div>
}
| 101110blog | trunk/Blog/Views/Account/ChangePassword.cshtml | HTML+Razor | mit | 1,765 |
@{
ViewBag.Title = "Change Password";
}
<h2>Change Password</h2>
<p>
Your password has been changed successfully.
</p>
| 101110blog | trunk/Blog/Views/Account/ChangePasswordSuccess.cshtml | HTML+Razor | mit | 139 |
@{
ViewBag.Title = "EditPost";
Layout = "~/Views/Admin/_AdminLayout.cshtml";
}
<h2>EditPost</h2>
| 101110blog | trunk/Blog/Views/Admin/EditPost.cshtml | HTML+Razor | mit | 115 |
@{
ViewBag.Title = "EditUser";
Layout = "~/Views/Admin/_AdminLayout.cshtml";
}
<h2>EditUser</h2>
| 101110blog | trunk/Blog/Views/Admin/EditUser.cshtml | HTML+Razor | mit | 115 |
@{
ViewBag.Title = "CreatePost";
Layout = "~/Views/Admin/_AdminLayout.cshtml";
}
<h2>CreatePost</h2>
| 101110blog | trunk/Blog/Views/Admin/CreatePost.cshtml | HTML+Razor | mit | 119 |
@{
ViewBag.Title = "CreateUser";
Layout = "~/Views/Admin/_AdminLayout.cshtml";
}
<h2>CreateUser</h2>
| 101110blog | trunk/Blog/Views/Admin/CreateUser.cshtml | HTML+Razor | mit | 119 |
@{
ViewBag.Title = "Users";
Layout = "~/Views/Admin/_AdminLayout.cshtml";
}
<h2>Users</h2>
<table>
<tr>
<th>Login</th>
<th>Role</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<tr>
<td>admin</td>
<td>admin</td>
<td><a href="#">edit</a></td>
<td><a href="#">delete</a></td>
</tr>
<tr>
<td>editor</td>
<td>editor</td>
<td><a href="#">edit</a></td>
<td><a href="#">delete</a></td>
</tr>
<tr>
<td>user</td>
<td>user</td>
<td><a href="#">edit</a></td>
<td><a href="#">delete</a></td>
</tr>
<tr>
<td>mike</td>
<td>user</td>
<td><a href="#">edit</a></td>
<td><a href="#">delete</a></td>
</tr>
<tr>
<td>volia</td>
<td>admin</td>
<td><a href="#">edit</a></td>
<td><a href="#">delete</a></td>
</tr>
</table>
| 101110blog | trunk/Blog/Views/Admin/Users.cshtml | HTML+Razor | mit | 989 |
<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
</head>
<body>
<div class="page">
<div id="header">
<div id="title">
<h1>Admin Panel</h1>
</div>
<div id="logindisplay">
@Html.Partial("_LogOnPartial")
<div>@Html.ActionLink("Go to the website", "Index", "Home")</div>
</div>
<div id="menucontainer">
<ul id="menu">
<li>@Html.ActionLink("Posts", "AdminIndex", "Admin")</li>
<li>@Html.ActionLink("Users", "Users", "Admin")</li>
</ul>
</div>
</div>
<div id="main">
@RenderBody()
</div>
<div id="footer">
</div>
</div>
</body>
</html>
| 101110blog | trunk/Blog/Views/Admin/_AdminLayout.cshtml | HTML+Razor | mit | 1,025 |
@{
ViewBag.Title = "AdminIndex";
Layout = "~/Views/Admin/_AdminLayout.cshtml";
}
<h2>Posts</h2>
<table>
<tr>
<th>Title</th>
<th>Creator</th>
<th>Featured</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<tr>
<td>ASP.NET MVC Overview</td>
<td>admin</td>
<td>yes</td>
<td><a href="#">edit</a></td>
<td><a href="#">delete</a></td>
</tr>
<tr>
<td>ASP.NET MVC Overview ASP.NET ASP.NET</td>
<td>editr</td>
<td>no</td>
<td><a href="#">edit</a></td>
<td><a href="#">delete</a></td>
</tr>
<tr>
<td>ASP.NET MVC</td>
<td>admin</td>
<td>no</td>
<td><a href="#">edit</a></td>
<td><a href="#">delete</a></td>
</tr>
</table>
| 101110blog | trunk/Blog/Views/Admin/AdminIndex.cshtml | HTML+Razor | mit | 842 |
@{
ViewBag.Title = "About Us";
}
<h2>About</h2>
<p>
Put content here.
</p>
| 101110blog | trunk/Blog/Views/Home/About.cshtml | HTML+Razor | mit | 96 |
@{
ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<div class="feachured-posts">
<h3>Feachured Posts:</h3>
<ul>
<li>
<h4><a href="#">ASP.NET MVC Overview</a></h4>
<p>The Model-View-Controller (MVC) architectural pattern separates...</p>
</li>
<li>
<h4><a href="#">ASP.NET MVC Overview</a></h4>
<p>The Model-View-Controller (MVC) architectural pattern separates...</p>
</li>
<li>
<h4><a href="#">ASP.NET MVC Overview</a></h4>
<p>The Model-View-Controller (MVC) architectural pattern separates...</p>
</li>
<li>
<h4><a href="#">ASP.NET MVC Overview</a></h4>
<p>The Model-View-Controller (MVC) architectural pattern separates...</p>
</li>
</ul>
</div>
<div class="main">
<div class="content">
<div class="post">
<h3><a href="#">ASP.NET MVC Overview</a></h3>
<span>Posted on <a href="#">April 29, 2012</a> by <a href="#">admin</a></span>
<p>The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller. The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for creating Web applications. The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc assembly.
<a href="#">read more >> </a>
</p>
<span><a href="#">10 comments</a></span>
<div class="tags">
<h6>Tags:</h6>
<ul>
<li><a href="#">ASP.NET</a>,</li>
<li><a href="#">MVC</a>,</li>
<li><a href="#">Patterns</a>,</li>
<li><a href="#">Web Development</a></li>
</ul>
</div>
</div>
<div class="post">
<h3><a href="#">ASP.NET MVC Overview</a></h3>
<span>Posted on <a href="#">April 29, 2012</a> by <a href="#">admin</a></span>
<p>The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller. The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for creating Web applications. The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc assembly.
<a href="#">read more >> </a>
</p>
<span><a href="#">10 comments</a></span>
<div class="tags">
<h6>Tags:</h6>
<ul>
<li><a href="#">ASP.NET</a>,</li>
<li><a href="#">MVC</a>,</li>
<li><a href="#">Patterns</a>,</li>
<li><a href="#">Web Development</a></li>
</ul>
</div>
</div>
<div class="post">
<h3><a href="#">ASP.NET MVC Overview</a></h3>
<span>Posted on <a href="#">April 29, 2012</a> by <a href="#">admin</a></span>
<p>The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller. The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for creating Web applications. The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc assembly.
<a href="#">read more >> </a>
</p>
<span><a href="#">10 comments</a></span>
<div class="tags">
<h6>Tags:</h6>
<ul>
<li><a href="#">ASP.NET</a>,</li>
<li><a href="#">MVC</a>,</li>
<li><a href="#">Patterns</a>,</li>
<li><a href="#">Web Development</a></li>
</ul>
</div>
</div>
<div class="pagination">
<ul class="pages">
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li><a href="#">6</a></li>
</ul>
</div>
</div>
<div class="sidebar">
<div class="tags">
<h5>Tags:</h5>
<ul>
<li><a href="#">MVC</a></li>
<li><a href="#">Content Map</a></li>
<li><a href="#">Controllers</a></li>
<li><a href="#">Routing</a></li>
<li><a href="#">Views</a></li>
<li><a href="#">Models</a></li>
<li><a href="#">Razor</a></li>
<li><a href="#">JavaScript</a></li>
<li><a href="#">Ajax</a></li>
<li><a href="#">MVC</a></li>
<li><a href="#">Content Map</a></li>
<li><a href="#">Controllers</a></li>
<li><a href="#">Routing</a></li>
<li><a href="#">Views</a></li>
<li><a href="#">Models</a></li>
<li><a href="#">Razor</a></li>
<li><a href="#">JavaScript</a></li>
<li><a href="#">Ajax</a></li>
<li><a href="#">MVC</a></li>
<li><a href="#">Content Map</a></li>
<li><a href="#">Controllers</a></li>
<li><a href="#">Routing</a></li>
<li><a href="#">Views</a></li>
<li><a href="#">Models</a></li>
<li><a href="#">Razor</a></li>
<li><a href="#">JavaScript</a></li>
<li><a href="#">Ajax</a></li>
</ul>
</div>
</div>
</div> | 101110blog | trunk/Blog/Views/Home/Index.cshtml | HTML+Razor | mit | 6,500 |
<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
</head>
<body>
<div class="page">
<div id="header">
<div id="title">
<h1>My MVC Application</h1>
</div>
<div id="logindisplay">
@Html.Partial("_LogOnPartial")
<div>@Html.ActionLink("Admin Panel", "AdminIndex", "Admin")</div>
</div>
@*<div id="menucontainer">
<ul id="menu">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
</ul>
</div>*@
</div>
<div id="main">
@RenderBody()
</div>
<div id="footer">
</div>
</div>
</body>
</html>
| 101110blog | trunk/Blog/Views/Shared/_Layout.cshtml | HTML+Razor | mit | 1,042 |
@if(Request.IsAuthenticated) {
<text>Welcome <strong>@User.Identity.Name</strong>!
[ @Html.ActionLink("Log Off", "LogOff", "Account") ]</text>
}
else {
@:[ @Html.ActionLink("Log On", "LogOn", "Account") ]
}
| 101110blog | trunk/Blog/Views/Shared/_LogOnPartial.cshtml | HTML+Razor | mit | 229 |
@model System.Web.Mvc.HandleErrorInfo
@{
ViewBag.Title = "Error";
}
<h2>
Sorry, an error occurred while processing your request.
</h2>
| 101110blog | trunk/Blog/Views/Shared/Error.cshtml | HTML+Razor | mit | 157 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Blog.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC Blog!";
return View();
}
public ActionResult About()
{
return View();
}
}
}
| 101110blog | trunk/Blog/Controllers/HomeController.cs | C# | mit | 452 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Blog.Models;
namespace Blog.Controllers
{
public class AccountController : Controller
{
//
// GET: /Account/LogOn
public ActionResult LogOn()
{
return View();
}
//
// POST: /Account/LogOn
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/LogOff
public ActionResult LogOff()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Home");
}
//
// GET: /Account/Register
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ChangePassword
[Authorize]
public ActionResult ChangePassword()
{
return View();
}
//
// POST: /Account/ChangePassword
[Authorize]
[HttpPost]
public ActionResult ChangePassword(ChangePasswordModel model)
{
if (ModelState.IsValid)
{
// ChangePassword will throw an exception rather
// than return false in certain failure scenarios.
bool changePasswordSucceeded;
try
{
MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
}
catch (Exception)
{
changePasswordSucceeded = false;
}
if (changePasswordSucceeded)
{
return RedirectToAction("ChangePasswordSuccess");
}
else
{
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ChangePasswordSuccess
public ActionResult ChangePasswordSuccess()
{
return View();
}
#region Status Codes
private static string ErrorCodeToString(MembershipCreateStatus createStatus)
{
// See http://go.microsoft.com/fwlink/?LinkID=177550 for
// a full list of status codes.
switch (createStatus)
{
case MembershipCreateStatus.DuplicateUserName:
return "User name already exists. Please enter a different user name.";
case MembershipCreateStatus.DuplicateEmail:
return "A user name for that e-mail address already exists. Please enter a different e-mail address.";
case MembershipCreateStatus.InvalidPassword:
return "The password provided is invalid. Please enter a valid password value.";
case MembershipCreateStatus.InvalidEmail:
return "The e-mail address provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidAnswer:
return "The password retrieval answer provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidQuestion:
return "The password retrieval question provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidUserName:
return "The user name provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.ProviderError:
return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
case MembershipCreateStatus.UserRejected:
return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
default:
return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
}
}
#endregion
}
}
| 101110blog | trunk/Blog/Controllers/AccountController.cs | C# | mit | 6,764 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Blog.Controllers
{
public class AdminController : Controller
{
//
// GET: /Admin/
public ActionResult AdminIndex()
{
return View();
}
public ActionResult Users()
{
return View();
}
}
}
| 101110blog | trunk/Blog/Controllers/AdminController.cs | C# | mit | 432 |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Web.Mvc;
using System.Web.Security;
namespace Blog.Models
{
public class ChangePasswordModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class LogOnModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
}
| 101110blog | trunk/Blog/Models/AccountModels.cs | C# | mit | 2,123 |
<%@ Application Codebehind="Global.asax.cs" Inherits="Blog.MvcApplication" Language="C#" %>
| 101110blog | trunk/Blog/Global.asax | ASP.NET | mit | 96 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Blog")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Blog")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b61b4636-870f-41bd-a2d0-048c47d532dc")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 101110blog | trunk/Blog/Properties/AssemblyInfo.cs | C# | mit | 1,379 |
/*----------------------------------------------------------
The base color for this template is #5c87b2. If you'd like
to use a different color start by replacing all instances of
#5c87b2 with your new color.
----------------------------------------------------------*/
body {
background-color: #5c87b2;
font-size: .85em;
font-family: "Trebuchet MS", Verdana, Helvetica, Sans-Serif;
margin: 0;
padding: 0;
color: #696969;
}
a:link {
color: #034af3;
text-decoration: underline;
}
a:visited {
color: #505abc;
}
a:hover {
color: #1d60ff;
text-decoration: none;
}
a:active {
color: #12eb87;
}
p, ul {
margin-bottom: 20px;
line-height: 1.6em;
}
header,
footer,
nav,
section {
display: block;
}
/* HEADINGS
----------------------------------------------------------*/
h1, h2, h3, h4, h5, h6 {
font-size: 1.5em;
color: #000;
}
h1 {
font-size: 2em;
padding-bottom: 0;
margin-bottom: 0;
}
h2 {
padding: 0 0 10px 0;
}
h3 {
font-size: 1.2em;
}
h4 {
font-size: 1.1em;
}
h5, h6 {
font-size: 1em;
}
/* PRIMARY LAYOUT ELEMENTS
----------------------------------------------------------*/
/* you can specify a greater or lesser percentage for the
page width. Or, you can specify an exact pixel width. */
.page {
width: 940px;
margin-left: auto;
margin-right: auto;
}
header, #header {
position: relative;
margin-bottom: 0px;
color: #000;
padding: 0;
min-height:80px
}
header h1, #header h1 {
font-weight: bold;
padding: 5px 0;
margin: 0;
color: #fff;
border: none;
line-height: 2em;
font-size: 32px !important;
text-shadow: 1px 1px 2px #111;
}
#main {
padding: 30px 30px 15px 30px;
background-color: #fff;
border-radius: 4px 4px 0 0;
-webkit-border-radius: 4px 4px 0 0;
-moz-border-radius: 4px 4px 0 0;
}
footer,
#footer {
background-color: #fff;
color: #999;
padding: 10px 0;
text-align: center;
line-height: normal;
margin: 0 0 30px 0;
font-size: .9em;
border-radius: 0 0 4px 4px;
-webkit-border-radius: 0 0 4px 4px;
-moz-border-radius: 0 0 4px 4px;
}
/* TAB MENU
----------------------------------------------------------*/
ul#menu {
border-bottom: 1px #5C87B2 solid;
padding: 0 0 2px;
position: relative;
margin: 0;
text-align: right;
}
ul#menu li {
display: inline;
list-style: none;
}
ul#menu li#greeting {
padding: 10px 20px;
font-weight: bold;
text-decoration: none;
line-height: 2.8em;
color: #fff;
}
ul#menu li a {
padding: 10px 20px;
font-weight: bold;
text-decoration: none;
line-height: 2.8em;
background-color: #e8eef4;
color: #034af3;
border-radius: 4px 4px 0 0;
-webkit-border-radius: 4px 4px 0 0;
-moz-border-radius: 4px 4px 0 0;
}
ul#menu li a:hover {
background-color: #fff;
text-decoration: none;
}
ul#menu li a:active {
background-color: #a6e2a6;
text-decoration: none;
}
ul#menu li.selected a {
background-color: #fff;
color: #000;
}
/* FORM LAYOUT ELEMENTS
----------------------------------------------------------*/
fieldset {
border: 1px solid #ddd;
padding: 0 1.4em 1.4em 1.4em;
margin: 0 0 1.5em 0;
}
legend {
font-size: 1.2em;
font-weight: bold;
}
textarea {
min-height: 75px;
}
input[type="text"],
input[type="password"] {
border: 1px solid #ccc;
padding: 2px;
font-size: 1.2em;
color: #444;
width: 200px;
}
select {
border: 1px solid #ccc;
padding: 2px;
font-size: 1.2em;
color: #444;
}
input[type="submit"] {
font-size: 1.2em;
padding: 5px;
}
/* TABLE
----------------------------------------------------------*/
table {
border: solid 1px #e8eef4;
border-collapse: collapse;
}
table td {
padding: 5px;
border: solid 1px #e8eef4;
}
table th {
padding: 6px 5px;
text-align: left;
background-color: #e8eef4;
border: solid 1px #e8eef4;
}
/* MISC
----------------------------------------------------------*/
.clear {
clear: both;
}
.error {
color: Red;
}
nav,
#menucontainer {
margin-top: 40px;
}
div#title {
display: block;
float: left;
text-align: left;
}
#logindisplay {
font-size: 1.1em;
display: block;
text-align: right;
margin: 10px;
color: White;
}
#logindisplay a:link {
color: white;
text-decoration: underline;
}
#logindisplay a:visited {
color: white;
text-decoration: underline;
}
#logindisplay a:hover {
color: white;
text-decoration: none;
}
/* Styles for validation helpers
-----------------------------------------------------------*/
.field-validation-error {
color: #ff0000;
}
.field-validation-valid {
display: none;
}
.input-validation-error {
border: 1px solid #ff0000;
background-color: #ffeeee;
}
.validation-summary-errors {
font-weight: bold;
color: #ff0000;
}
.validation-summary-valid {
display: none;
}
/* Styles for editor and display helpers
----------------------------------------------------------*/
.display-label,
.editor-label {
margin: 1em 0 0 0;
}
.display-field,
.editor-field {
margin: 0.5em 0 0 0;
}
.text-box {
width: 30em;
}
.text-box.multi-line {
height: 6.5em;
}
.tri-state {
width: 6em;
}
.feachured-posts {}
.feachured-posts ul {}
.feachured-posts ul:after {visibility:hidden; display:block; font-size:0; content:" "; clear:both; height:0;}
.feachured-posts ul li {float:left;width:160px;list-style:none;margin-right:20px}
.feachured-posts ul li p {font-size:11px}
.feachured-posts ul li h4 {font-size:14px;}
.main {}
.main:after {visibility:hidden; display:block; font-size:0; content:" "; clear:both; height:0;}
.content {width:650px;float:left;}
.sidebar {width:140px;float:right}
.post {border-top:1px solid #666;}
.post:first-child {border-top:none;}
.post h3 {}
.post h3 a{}
.post h3 a:hover {}
.post span {display:block;clear:both}
.post span a {}
.post span a:hover {}
.post p {}
.post .tags {margin-top:20px;margin-bottom:20px}
.post .tags:after {visibility:hidden; display:block; font-size:0; content:" "; clear:both; height:0;}
.post h6 {float:left;-webkit-margin-before:0;-webkit-margin-after:0;margin-right:10px;}
.post ul {margin-left:0;-webkit-padding-start:0;float:left;-webkit-margin-before:0;-webkit-margin-after:0;}
.post ul:after {visibility:hidden; display:block; font-size:0; content:" "; clear:both; height:0;}
.post ul li {float:left;margin-right:5px;list-style:none}
.post ul li a {}
.post ul li a:hover {}
.pagination:after {visibility:hidden; display:block; font-size:0; content:" "; clear:both; height:0;}
ul.pages {float:right;-webkit-padding-start:0;-webkit-margin-before:0;-webkit-margin-after:0}
ul.pages:after {visibility:hidden; display:block; font-size:0; content:" "; clear:both; height:0;}
ul.pages li {float:left;margin-left:12px;list-style:none;}
ul.pages li a {}
ul.pages li a:hover {}
.sidebar {}
.tags {}
.sidebar h5 {}
.tags ul {-webkit-padding-start:0;-webkit-margin-before:0;-webkit-margin-after:0}
.tags ul:after {visibility:hidden; display:block; font-size:0; content:" "; clear:both; height:0;}
.tags ul li {float:left;list-style:none;margin-right:10px;}
.tags ul li a {}
.tags ul li a:hover {} | 101110blog | trunk/Blog/Content/Site.css | CSS | mit | 7,990 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Blog
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
} | 101110blog | trunk/Blog/Global.asax.cs | C# | mit | 1,181 |
r -s c.r | 1000tool | src/run.bat | Batchfile | asf20 | 8 |
[Setup]
AppName=1000tool
AppVersion=1.5
DefaultDirName={pf}\1000tool
DefaultGroupName=1000tool
UninstallDisplayIcon={app}\r.exe
Compression=lzma2
SolidCompression=yes
OutputDir=.
OutputBaseFilename=1000setup
[Files]
Source: c.r; DestDir: {app};
Source: r.exe; DestDir: {app};
Source: procxp\*; DestDir: {app}\procxp;
Source: Everything\*; DestDir: {app}\Everything;
Source: npp\*; DestDir: {app}\npp; Flags: recursesubdirs;
Source: usbeject\*; DestDir: {app}\usbeject;
[Icons]
Name: "{group}\1000tool"; Filename: {app}\r.exe; Parameters: "-s c.r";
Name: {group}\Uninstall; Filename: {app}\unins000.exe;
[Run]
Filename: {app}\r.exe; Parameters: "-s c.r"; Flags: NoWait ShellExec PostInstall; Description: AppStarter;
| 1000tool | src/1000tsetup.iss | Inno Setup | asf20 | 750 |
/* Copyright [2011] [University of Rostock]
*
* 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.
*****************************************************************************/
package org.ws4d.coap.test;
import org.ws4d.coap.connection.BasicCoapChannelManager;
import org.ws4d.coap.interfaces.CoapChannelManager;
import org.ws4d.coap.interfaces.CoapRequest;
import org.ws4d.coap.interfaces.CoapResponse;
import org.ws4d.coap.interfaces.CoapServer;
import org.ws4d.coap.interfaces.CoapServerChannel;
import org.ws4d.coap.messages.CoapMediaType;
import org.ws4d.coap.messages.CoapResponseCode;
public class PlugtestSeparateResponseCoapServer implements CoapServer {
private static final int PORT = 5683;
static int counter = 0;
CoapResponse response = null;
CoapServerChannel channel = null;
int separateResponseTimeMs = 4000;
public void start(int separateResponseTimeMs){
CoapChannelManager channelManager = BasicCoapChannelManager.getInstance();
channelManager.createServerListener(this, PORT);
this.separateResponseTimeMs = separateResponseTimeMs;
}
@Override
public CoapServer onAccept(CoapRequest request) {
System.out.println("Accept connection...");
return this;
}
@Override
public void onRequest(CoapServerChannel channel, CoapRequest request) {
System.out.println("Received message: " + request.toString());
this.channel = channel;
response = channel.createSeparateResponse(request, CoapResponseCode.Content_205);
(new Thread( new SendDelayedResponse())).start();
}
public class SendDelayedResponse implements Runnable
{
public void run()
{
response.setContentType(CoapMediaType.text_plain);
response.setPayload("payload...".getBytes());
try {
Thread.sleep(separateResponseTimeMs);
} catch (InterruptedException e) {
e.printStackTrace();
}
channel.sendSeparateResponse(response);
System.out.println("Send separate Response: " + response.toString());
}
}
@Override
public void onSeparateResponseFailed(CoapServerChannel channel) {
System.out.println("Separate Response failed");
}
}
| 11106027-gokul | ws4d-jcoap-plugtest/src/org/ws4d/coap/test/PlugtestSeparateResponseCoapServer.java | Java | asf20 | 2,650 |
/**
* Server Application for Plugtest 2012, Paris, France
*
* Execute with argument Identifier (e.g., TD_COAP_CORE_01)
*/
package org.ws4d.coap.test;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.ws4d.coap.connection.BasicCoapChannelManager;
import org.ws4d.coap.connection.BasicCoapSocketHandler;
import org.ws4d.coap.rest.CoapResourceServer;
import org.ws4d.coap.test.resources.LongPathResource;
import org.ws4d.coap.test.resources.QueryResource;
import org.ws4d.coap.test.resources.TestResource;
/**
* @author Nico Laum <nico.laum@uni-rostock.de>
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*
*/
public class PlugtestServer {
private static PlugtestServer plugtestServer;
private CoapResourceServer resourceServer;
private static Logger logger = Logger
.getLogger(BasicCoapSocketHandler.class.getName());
/**
* @param args
*/
public static void main(String[] args) {
if (args.length > 1 || args.length < 1) {
System.err.println("illegal number of arguments");
System.exit(1);
}
logger.setLevel(Level.WARNING);
plugtestServer = new PlugtestServer();
plugtestServer.start(args[0]);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("PlugtestServer is now stopping.");
System.out.println("===END===");
}
});
}
public void start(String testId) {
System.out.println("===Run Test Server: " + testId + "===");
init();
if (testId.equals("TD_COAP_CORE_01")) {
resourceServer.createResource(new TestResource());
run();
} else if (testId.equals("TD_COAP_CORE_02")) {
/* Nothing to setup, POST creates new resource */
run();
} else if (testId.equals("TD_COAP_CORE_03")) {
resourceServer.createResource(new TestResource());
run();
} else if (testId.equals("TD_COAP_CORE_04")) {
resourceServer.createResource(new TestResource());
run();
} else if (testId.equals("TD_COAP_CORE_05")) {
resourceServer.createResource(new TestResource());
run();
} else if (testId.equals("TD_COAP_CORE_06")) {
/* Nothing to setup, POST creates new resource */
run();
} else if (testId.equals("TD_COAP_CORE_07")) {
resourceServer.createResource(new TestResource());
run();
} else if (testId.equals("TD_COAP_CORE_08")) {
resourceServer.createResource(new TestResource());
run();
} else if (testId.equals("TD_COAP_CORE_09")) {
/*
* === SPECIAL CASE: Separate Response: for these tests we cannot
* use the resource server
*/
PlugtestSeparateResponseCoapServer server = new PlugtestSeparateResponseCoapServer();
server.start(TestConfiguration.SEPARATE_RESPONSE_TIME_MS);
} else if (testId.equals("TD_COAP_CORE_10")) {
resourceServer.createResource(new TestResource());
run();
} else if (testId.equals("TD_COAP_CORE_11")) {
resourceServer.createResource(new TestResource());
run();
} else if (testId.equals("TD_COAP_CORE_12")) {
resourceServer.createResource(new LongPathResource());
run();
} else if (testId.equals("TD_COAP_CORE_13")) {
resourceServer.createResource(new QueryResource());
run();
} else if (testId.equals("TD_COAP_CORE_14")) {
resourceServer.createResource(new TestResource());
run();
} else if (testId.equals("TD_COAP_CORE_15")) {
/*
* === SPECIAL CASE: Separate Response: for these tests we cannot
* use the resource server
*/
PlugtestSeparateResponseCoapServer server = new PlugtestSeparateResponseCoapServer();
server.start(TestConfiguration.SEPARATE_RESPONSE_TIME_MS);
} else if (testId.equals("TD_COAP_CORE_16")) {
/*
* === SPECIAL CASE: Separate Response: for these tests we cannot
* use the resource server
*/
PlugtestSeparateResponseCoapServer server = new PlugtestSeparateResponseCoapServer();
server.start(TestConfiguration.SEPARATE_RESPONSE_TIME_MS);
} else if (testId.equals("TD_COAP_LINK_01")) {
resourceServer.createResource(new LongPathResource());
resourceServer.createResource(new TestResource());
run();
} else if (testId.equals("TD_COAP_LINK_02")) {
resourceServer.createResource(new LongPathResource());
resourceServer.createResource(new TestResource());
run();
} else if (testId.equals("TD_COAP_BLOCK_01")) {
} else if (testId.equals("TD_COAP_BLOCK_02")) {
} else if (testId.equals("TD_COAP_BLOCK_03")) {
} else if (testId.equals("TD_COAP_BLOCK_04")) {
} else if (testId.equals("TD_COAP_OBS_01")) {
} else if (testId.equals("TD_COAP_OBS_02")) {
} else if (testId.equals("TD_COAP_OBS_03")) {
} else if (testId.equals("TD_COAP_OBS_04")) {
} else if (testId.equals("TD_COAP_OBS_05")) {
} else {
System.out.println("unknown test case");
System.exit(-1);
}
}
private void init() {
BasicCoapChannelManager.getInstance().setMessageId(2000);
if (resourceServer != null)
resourceServer.stop();
resourceServer = new CoapResourceServer();
}
private void run() {
try {
resourceServer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 11106027-gokul | ws4d-jcoap-plugtest/src/org/ws4d/coap/test/PlugtestServer.java | Java | asf20 | 5,128 |
/**
* Server Application for Plugtest 2012, Paris, France
*
* Execute with argument Identifier (e.g., TD_COAP_CORE_01)
*/
package org.ws4d.coap.test;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.ws4d.coap.connection.BasicCoapChannelManager;
import org.ws4d.coap.connection.BasicCoapSocketHandler;
import org.ws4d.coap.rest.CoapResourceServer;
import org.ws4d.coap.test.resources.LongPathResource;
import org.ws4d.coap.test.resources.QueryResource;
import org.ws4d.coap.test.resources.TestResource;
/**
* @author Nico Laum <nico.laum@uni-rostock.de>
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*
*/
public class CompletePlugtestServer {
private static CompletePlugtestServer plugtestServer;
private CoapResourceServer resourceServer;
private static Logger logger = Logger
.getLogger(BasicCoapSocketHandler.class.getName());
/**
* @param args
*/
public static void main(String[] args) {
logger.setLevel(Level.WARNING);
plugtestServer = new CompletePlugtestServer();
plugtestServer.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("PlugtestServer is now stopping.");
System.out.println("===END===");
}
});
}
public void start() {
System.out.println("===Run Test Server ===");
init();
resourceServer.createResource(new TestResource());
resourceServer.createResource(new LongPathResource());
resourceServer.createResource(new QueryResource());
run();
}
private void init() {
BasicCoapChannelManager.getInstance().setMessageId(2000);
if (resourceServer != null)
resourceServer.stop();
resourceServer = new CoapResourceServer();
}
private void run() {
try {
resourceServer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 11106027-gokul | ws4d-jcoap-plugtest/src/org/ws4d/coap/test/CompletePlugtestServer.java | Java | asf20 | 1,894 |
/**
* Client Application for Plugtest 2012, Paris, France
*
* Execute with argument Identifier (e.g., TD_COAP_CORE_01)
*/
package org.ws4d.coap.test;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.ws4d.coap.connection.BasicCoapChannelManager;
import org.ws4d.coap.connection.BasicCoapSocketHandler;
import org.ws4d.coap.interfaces.CoapChannelManager;
import org.ws4d.coap.interfaces.CoapClient;
import org.ws4d.coap.interfaces.CoapClientChannel;
import org.ws4d.coap.interfaces.CoapRequest;
import org.ws4d.coap.interfaces.CoapResponse;
import org.ws4d.coap.messages.CoapEmptyMessage;
import org.ws4d.coap.messages.CoapMediaType;
import org.ws4d.coap.messages.CoapRequestCode;
/**
* @author Nico Laum <nico.laum@uni-rostock.de>
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*
*/
public class PlugtestClient implements CoapClient{
CoapChannelManager channelManager = null;
CoapClientChannel clientChannel = null;
CoapRequest request = null;
private static Logger logger = Logger.getLogger(BasicCoapSocketHandler.class.getName());
boolean exitAfterResponse = true;
String serverAddress = null;
int serverPort = 0;
String filter = null;
public static void main(String[] args) {
if (args.length > 4 || args.length < 4) {
System.err.println("illegal number of arguments");
System.exit(1);
}
logger.setLevel(Level.WARNING);
PlugtestClient client = new PlugtestClient();
client.start(args[0], Integer.parseInt(args[1]), args[2], args[3]);
}
public void start(String serverAddress, int serverPort, String testcase, String filter){
System.out.println("===START=== (Run Test Client: " + testcase + ")");
String testId = testcase;
this.serverAddress = serverAddress;
this.serverPort = serverPort;
this.filter = filter;
if (testId.equals("TD_COAP_CORE_01")) {
init(true, CoapRequestCode.GET);
request.setUriPath("/test");
}
else if (testId.equals("TD_COAP_CORE_02")) {
init(true, CoapRequestCode.POST);
request.setUriPath("/test");
request.setPayload("Content of new resource /test");
request.setContentType(CoapMediaType.text_plain);
}
else if (testId.equals("TD_COAP_CORE_03")) {
init(true, CoapRequestCode.PUT);
request.setUriPath("/test");
request.setPayload("Content of new resource /test");
request.setContentType(CoapMediaType.text_plain);
}
else if (testId.equals("TD_COAP_CORE_04")) {
init(true, CoapRequestCode.DELETE);
request.setUriPath("/test");
}
else if (testId.equals("TD_COAP_CORE_05")) {
init(false, CoapRequestCode.GET);
request.setUriPath("/test");
}
else if (testId.equals("TD_COAP_CORE_06")) {
init(false, CoapRequestCode.POST);
request.setUriPath("/test");
request.setPayload("Content of new resource /test");
request.setContentType(CoapMediaType.text_plain);
}
else if (testId.equals("TD_COAP_CORE_07")) {
init(false, CoapRequestCode.PUT);
request.setUriPath("/test");
request.setPayload("Content of new resource /test");
request.setContentType(CoapMediaType.text_plain);
}
else if (testId.equals("TD_COAP_CORE_08")) {
init(false, CoapRequestCode.DELETE);
request.setUriPath("/test");
}
else if (testId.equals("TD_COAP_CORE_09")) {
init(true, CoapRequestCode.GET);
request.setUriPath("/separate");
}
else if (testId.equals("TD_COAP_CORE_10")) {
init(true, CoapRequestCode.GET);
request.setUriPath("/test");
request.setToken("AABBCCDD".getBytes());
}
else if (testId.equals("TD_COAP_CORE_11")) {
init(true, CoapRequestCode.GET);
request.setUriPath("/test");
}
else if (testId.equals("TD_COAP_CORE_12")) {
init(true, CoapRequestCode.GET);
request.setUriPath("/seg1/seg2/seg3");
}
else if (testId.equals("TD_COAP_CORE_13")) {
init(true, CoapRequestCode.GET);
request.setUriPath("/query");
request.setUriQuery("first=1&second=2&third=3");
}
else if (testId.equals("TD_COAP_CORE_14")) {
init(true, CoapRequestCode.GET);
request.setUriPath("/test");
}
else if (testId.equals("TD_COAP_CORE_15")) {
init(true, CoapRequestCode.GET);
request.setUriPath("/separate");
}
else if (testId.equals("TD_COAP_CORE_16")) {
init(false, CoapRequestCode.GET);
request.setUriPath("/separate");
}
else if (testId.equals("TD_COAP_LINK_01")) {
init(false, CoapRequestCode.GET);
request.setUriPath("/.well-known/core");
}
else if (testId.equals("TD_COAP_LINK_02")) {
init(false, CoapRequestCode.GET);
request.setUriPath("/.well-known/core");
request.setUriQuery("rt=" + this.filter);
}
else {
System.out.println("===Failure=== (unknown test case)");
System.exit(-1);
}
run();
}
public void init(boolean reliable, CoapRequestCode requestCode) {
channelManager = BasicCoapChannelManager.getInstance();
channelManager.setMessageId(1000);
try {
clientChannel = channelManager.connect(this, InetAddress.getByName(this.serverAddress), this.serverPort);
if (clientChannel == null){
System.out.println("Connect failed.");
System.exit(-1);
}
request = clientChannel.createRequest(reliable, requestCode);
} catch (UnknownHostException e) {
e.printStackTrace();
System.exit(-1);
}
}
public void run() {
if(request.getPayload() != null){
System.out.println("Send Request: " + request.toString() + " (" + new String(request.getPayload()) +")");
}else {
System.out.println("Send Request: " + request.toString());
}
clientChannel.sendMessage(request);
}
@Override
public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer) {
System.out.println("Connection Failed");
System.exit(-1);
}
@Override
public void onResponse(CoapClientChannel channel, CoapResponse response) {
if (response.getPayload() != null){
System.out.println("Response: " + response.toString() + " (" + new String(response.getPayload()) +")");
} else {
System.out.println("Response: " + response.toString());
}
if (exitAfterResponse){
System.out.println("===END===");
System.exit(0);
}
}
public class WaitAndExit implements Runnable
{
public void run()
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("===END===");
System.exit(0);
}
}
}
| 11106027-gokul | ws4d-jcoap-plugtest/src/org/ws4d/coap/test/PlugtestClient.java | Java | asf20 | 6,486 |
#!/bin/bash
# run "./runTests.sh" for verbose output
# for short output, run
# ./runTests.sh | grep FAILED
# ./runTests.sh | grep PASSED
#master branch
SERVER_CLASS="org.ws4d.coap.test.PlugtestServer"
CLIENT_CLASS="org.ws4d.coap.test.PlugtestClient"
CLASSPATH="bin/:../ws4d-jcoap/bin"
LOG_DIR="log"
REF_LOG_DIR="logref"
EXEC_SERVER=""
EXEC_CLIENT=""
build_exec_string() {
TEST=$1
EXEC_SERVER="java -cp $CLASSPATH $SERVER_CLASS $TEST > $LOG_DIR/${TEST}_SERVER.txt &"
EXEC_CLIENT="java -cp $CLASSPATH $CLIENT_CLASS $TEST > $LOG_DIR/${TEST}_CLIENT.txt &"
}
run_test() {
TEST=$1
echo "Running Test $TEST"
build_exec_string $TEST
eval $EXEC_SERVER
eval $EXEC_CLIENT
sleep 3
killall java >/dev/null 2>/dev/null
sleep 1
diff -i -b -B -q $LOG_DIR/${TEST}_SERVER.txt $REF_LOG_DIR/${TEST}_SERVER.txt
if [ ! $? -eq 0 ]
then
echo "FAILED Server $TEST"
else
echo "PASSED Server $TEST"
fi
diff -i -b -B -q $LOG_DIR/${TEST}_CLIENT.txt $REF_LOG_DIR/${TEST}_CLIENT.txt
if [ ! $? -eq 0 ]
then
echo "FAILED Client $TEST"
else
echo "PASSED Client $TEST"
fi
}
killall java >/dev/null 2>/dev/null
sleep 1
mkdir -p $LOG_DIR
# CoAP CORE Tests
for i in 1 2 3 4 5 6 7 8 9
do
run_test TD_COAP_CORE_0$i
done
for i in 10 11 12 13 14 15 16
do
run_test TD_COAP_CORE_$i
done
# CoAP Link Tests
#for i in 1 2
#do
# run_test TD_COAP_LINK_0$i
#done
# CoAP Block Tests
#for i in 1 2 3 4
#do
# run_test TD_COAP_BLOCK_0$i
#done
# CoAP Observation Tests
#for i in 1 2 3 4 5
#do
# run_test TD_COAP_OBS_0$i
#done
| 11106027-gokul | ws4d-jcoap-plugtest/runTests.sh | Shell | asf20 | 1,550 |
package org.ws4d.coap.connection;
import java.net.InetAddress;
public class ChannelKey {
public InetAddress inetAddr;
public int port;
public ChannelKey(InetAddress inetAddr, int port) {
this.inetAddr = inetAddr;
this.port = port;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((inetAddr == null) ? 0 : inetAddr.hashCode());
result = prime * result + port;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ChannelKey other = (ChannelKey) obj;
if (inetAddr == null) {
if (other.inetAddr != null)
return false;
} else if (!inetAddr.equals(other.inetAddr))
return false;
if (port != other.port)
return false;
return true;
}
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/connection/ChannelKey.java | Java | asf20 | 913 |
/* Copyright [2011] [University of Rostock]
*
* 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.
*****************************************************************************/
package org.ws4d.coap.connection;
import java.net.InetAddress;
import org.apache.log4j.Logger;
import org.ws4d.coap.interfaces.CoapChannel;
import org.ws4d.coap.interfaces.CoapChannelManager;
import org.ws4d.coap.interfaces.CoapMessage;
import org.ws4d.coap.interfaces.CoapSocketHandler;
import org.ws4d.coap.messages.CoapBlockOption.CoapBlockSize;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
public abstract class BasicCoapChannel implements CoapChannel {
/* use the logger of the channel manager */
private final static Logger logger = Logger.getLogger(BasicCoapChannelManager.class);
protected CoapSocketHandler socketHandler = null;
protected CoapChannelManager channelManager = null;
protected InetAddress remoteAddress;
protected int remotePort;
protected int localPort;
CoapBlockSize maxReceiveBlocksize = null; //null means no block option
CoapBlockSize maxSendBlocksize = null; //null means no block option
public BasicCoapChannel(CoapSocketHandler socketHandler, InetAddress remoteAddress, int remotePort) {
this.socketHandler = socketHandler;
channelManager = socketHandler.getChannelManager();
this.remoteAddress = remoteAddress;
this.remotePort = remotePort;
this.localPort = socketHandler.getLocalPort(); //FIXME:can be 0 when socketHandler is not yet ready
}
@Override
public void sendMessage(CoapMessage msg) {
msg.setChannel(this);
socketHandler.sendMessage(msg);
}
@Override
public CoapBlockSize getMaxReceiveBlocksize() {
return maxReceiveBlocksize;
}
@Override
public void setMaxReceiveBlocksize(CoapBlockSize maxReceiveBlocksize) {
this.maxReceiveBlocksize = maxReceiveBlocksize;
}
@Override
public CoapBlockSize getMaxSendBlocksize() {
return maxSendBlocksize;
}
@Override
public void setMaxSendBlocksize(CoapBlockSize maxSendBlocksize) {
this.maxSendBlocksize = maxSendBlocksize;
}
@Override
public InetAddress getRemoteAddress() {
return remoteAddress;
}
@Override
public int getRemotePort() {
return remotePort;
}
/*A channel is identified (and therefore unique) by its remote address, remote port and the local port
* TODO: identify channel also by a token */
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + localPort;
result = prime * result
+ ((remoteAddress == null) ? 0 : remoteAddress.hashCode());
result = prime * result + remotePort;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BasicCoapChannel other = (BasicCoapChannel) obj;
if (localPort != other.localPort)
return false;
if (remoteAddress == null) {
if (other.remoteAddress != null)
return false;
} else if (!remoteAddress.equals(other.remoteAddress))
return false;
if (remotePort != other.remotePort)
return false;
return true;
}
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/connection/BasicCoapChannel.java | Java | asf20 | 3,897 |
/* Copyright [2011] [University of Rostock]
*
* 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.
*****************************************************************************/
package org.ws4d.coap.connection;
import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Random;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.ws4d.coap.Constants;
import org.ws4d.coap.interfaces.CoapChannelManager;
import org.ws4d.coap.interfaces.CoapClient;
import org.ws4d.coap.interfaces.CoapClientChannel;
import org.ws4d.coap.interfaces.CoapMessage;
import org.ws4d.coap.interfaces.CoapServer;
import org.ws4d.coap.interfaces.CoapServerChannel;
import org.ws4d.coap.interfaces.CoapSocketHandler;
import org.ws4d.coap.messages.BasicCoapRequest;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
public class BasicCoapChannelManager implements CoapChannelManager {
// global message id
private final static Logger logger = Logger.getLogger(BasicCoapChannelManager.class);
private int globalMessageId;
private static BasicCoapChannelManager instance;
private HashMap<Integer, SocketInformation> socketMap = new HashMap<Integer, SocketInformation>();
CoapServer serverListener = null;
private BasicCoapChannelManager() {
logger.addAppender(new ConsoleAppender(new SimpleLayout()));
// ALL | DEBUG | INFO | WARN | ERROR | FATAL | OFF:
logger.setLevel(Level.WARN);
initRandom();
}
public synchronized static CoapChannelManager getInstance() {
if (instance == null) {
instance = new BasicCoapChannelManager();
}
return instance;
}
/**
* Creates a new server channel
*/
@Override
public synchronized CoapServerChannel createServerChannel(CoapSocketHandler socketHandler, CoapMessage message, InetAddress addr, int port){
SocketInformation socketInfo = socketMap.get(socketHandler.getLocalPort());
if (socketInfo.serverListener == null) {
/* this is not a server socket */
throw new IllegalStateException("Invalid server socket");
}
if (!message.isRequest()){
throw new IllegalStateException("Incomming message is not a request message");
}
CoapServer server = socketInfo.serverListener.onAccept((BasicCoapRequest) message);
if (server == null){
/* Server rejected channel */
return null;
}
CoapServerChannel newChannel= new BasicCoapServerChannel( socketHandler, server, addr, port);
return newChannel;
}
/**
* Creates a new, global message id for a new COAP message
*/
@Override
public synchronized int getNewMessageID() {
if (globalMessageId < Constants.MESSAGE_ID_MAX) {
++globalMessageId;
} else
globalMessageId = Constants.MESSAGE_ID_MIN;
return globalMessageId;
}
@Override
public synchronized void initRandom() {
// generate random 16 bit messageId
Random random = new Random();
globalMessageId = random.nextInt(Constants.MESSAGE_ID_MAX + 1);
}
@Override
public void createServerListener(CoapServer serverListener, int localPort) {
if (!socketMap.containsKey(localPort)) {
try {
SocketInformation socketInfo = new SocketInformation(new BasicCoapSocketHandler(this, localPort), serverListener);
socketMap.put(localPort, socketInfo);
} catch (IOException e) {
e.printStackTrace();
}
} else {
/*TODO: raise exception: address already in use */
throw new IllegalStateException();
}
}
@Override
public CoapClientChannel connect(CoapClient client, InetAddress addr, int port) {
CoapSocketHandler socketHandler = null;
try {
socketHandler = new BasicCoapSocketHandler(this);
SocketInformation sockInfo = new SocketInformation(socketHandler, null);
socketMap.put(socketHandler.getLocalPort(), sockInfo);
return socketHandler.connect(client, addr, port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private class SocketInformation {
public CoapSocketHandler socketHandler = null;
public CoapServer serverListener = null;
public SocketInformation(CoapSocketHandler socketHandler,
CoapServer serverListener) {
super();
this.socketHandler = socketHandler;
this.serverListener = serverListener;
}
}
@Override
public void setMessageId(int globalMessageId) {
this.globalMessageId = globalMessageId;
}
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/connection/BasicCoapChannelManager.java | Java | asf20 | 5,219 |
/* Copyright [2011] [University of Rostock]
*
* 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.
*****************************************************************************/
package org.ws4d.coap.connection;
import java.io.ByteArrayOutputStream;
import java.net.InetAddress;
import org.ws4d.coap.interfaces.CoapClient;
import org.ws4d.coap.interfaces.CoapClientChannel;
import org.ws4d.coap.interfaces.CoapMessage;
import org.ws4d.coap.interfaces.CoapRequest;
import org.ws4d.coap.interfaces.CoapResponse;
import org.ws4d.coap.interfaces.CoapSocketHandler;
import org.ws4d.coap.messages.BasicCoapRequest;
import org.ws4d.coap.messages.BasicCoapResponse;
import org.ws4d.coap.messages.CoapBlockOption;
import org.ws4d.coap.messages.CoapBlockOption.CoapBlockSize;
import org.ws4d.coap.messages.CoapEmptyMessage;
import org.ws4d.coap.messages.CoapPacketType;
import org.ws4d.coap.messages.CoapRequestCode;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
public class BasicCoapClientChannel extends BasicCoapChannel implements CoapClientChannel {
CoapClient client = null;
ClientBlockContext blockContext = null;
CoapRequest lastRequest = null;
Object trigger = null;
public BasicCoapClientChannel(CoapSocketHandler socketHandler,
CoapClient client, InetAddress remoteAddress,
int remotePort) {
super(socketHandler, remoteAddress, remotePort);
this.client = client;
}
@Override
public void close() {
socketHandler.removeClientChannel(this);
}
@Override
public void handleMessage(CoapMessage message) {
if (message.isRequest()){
/* this is a client channel, no requests allowed */
message.getChannel().sendMessage(new CoapEmptyMessage(CoapPacketType.RST, message.getMessageID()));
return;
}
if (message.isEmpty() && message.getPacketType() == CoapPacketType.ACK){
/* this is the ACK of a separate response */
//TODO: implement a handler or listener, that informs a client when a sep. resp. ack was received
return;
}
if (message.getPacketType() == CoapPacketType.CON) {
/* this is a separate response */
/* send ACK */
this.sendMessage(new CoapEmptyMessage(CoapPacketType.ACK, message.getMessageID()));
}
/* check for blockwise transfer */
CoapBlockOption block2 = message.getBlock2();
if (blockContext == null && block2 != null){
/* initiate blockwise transfer */
blockContext = new ClientBlockContext(block2, maxReceiveBlocksize);
blockContext.setFirstRequest(lastRequest);
blockContext.setFirstResponse((CoapResponse) message);
}
if (blockContext!= null){
/*blocking option*/
if (!blockContext.addBlock(message, block2)){
/*this was not a correct block*/
/* TODO: implement either a RST or ignore this packet */
}
if (!blockContext.isFinished()){
/* TODO: implement a counter to avoid an infinity req/resp loop:
* if the same block is received more than x times -> rst the connection
* implement maxPayloadSize to avoid an infinity payload */
CoapBlockOption newBlock = blockContext.getNextBlock();
if (lastRequest == null){
/*TODO: this should never happen*/
System.out.println("ERROR: client channel: lastRequest == null");
} else {
/* create a new request for the next block */
BasicCoapRequest request = new BasicCoapRequest(lastRequest.getPacketType(), lastRequest.getRequestCode(), channelManager.getNewMessageID());
request.copyHeaderOptions((BasicCoapRequest) blockContext.getFirstRequest());
request.setBlock2(newBlock);
sendMessage(request);
}
/* TODO: implement handler, inform the client that a block (but not the complete message) was received*/
return;
}
/* blockwise transfer finished */
message.setPayload(blockContext.getPayload());
/* TODO: give the payload separately and leave the original message as they is*/
}
/* normal or separate response */
client.onResponse(this, (BasicCoapResponse) message);
}
@Override
public void lostConnection(boolean notReachable, boolean resetByServer) {
client.onConnectionFailed(this, notReachable, resetByServer);
}
@Override
public BasicCoapRequest createRequest(boolean reliable, CoapRequestCode requestCode) {
BasicCoapRequest msg = new BasicCoapRequest(
reliable ? CoapPacketType.CON : CoapPacketType.NON, requestCode,
channelManager.getNewMessageID());
msg.setChannel(this);
return msg;
}
@Override
public void sendMessage(CoapMessage msg) {
super.sendMessage(msg);
//TODO: check
lastRequest = (CoapRequest) msg;
}
// public DefaultCoapClientChannel(CoapChannelManager channelManager) {
// super(channelManager);
// }
//
// @Override
// public void connect(String remoteHost, int remotePort) {
// socket = null;
// if (remoteHost!=null && remotePort!=-1) {
// try {
// socket = new DatagramSocket();
// } catch (SocketException e) {
// e.printStackTrace();
// }
// }
//
// try {
// InetAddress address = InetAddress.getByName(remoteHost);
// socket.connect(address, remotePort);
// super.establish(socket);
// } catch (UnknownHostException e) {
// e.printStackTrace();
// }
// }
private class ClientBlockContext{
ByteArrayOutputStream payload = new ByteArrayOutputStream();
boolean finished = false;
CoapBlockSize blockSize; //null means no block option
CoapRequest request;
CoapResponse response;
public ClientBlockContext(CoapBlockOption blockOption, CoapBlockSize maxBlocksize) {
/* determine the right blocksize (min of remote and max)*/
if (maxBlocksize == null){
blockSize = blockOption.getBlockSize();
} else {
int max = maxBlocksize.getSize();
int remote = blockOption.getBlockSize().getSize();
if (remote < max){
blockSize = blockOption.getBlockSize();
} else {
blockSize = maxBlocksize;
}
}
}
public byte[] getPayload() {
return payload.toByteArray();
}
public boolean addBlock(CoapMessage msg, CoapBlockOption block){
int blockPos = block.getBytePosition();
int blockLength = msg.getPayloadLength();
int bufSize = payload.size();
/*TODO: check if payload length = blocksize (except for the last block)*/
if (blockPos > bufSize){
/* data is missing before this block */
return false;
} else if ((blockPos + blockLength) <= bufSize){
/* data already received */
return false;
}
int offset = bufSize - blockPos;
payload.write(msg.getPayload(), offset, blockLength - offset);
if (block.isLast()){
/* was this the last block */
finished = true;
}
return true;
}
public CoapBlockOption getNextBlock() {
int num = payload.size() / blockSize.getSize(); //ignore the rest (no rest should be there)
return new CoapBlockOption(num, false, blockSize);
}
public boolean isFinished() {
return finished;
}
public CoapRequest getFirstRequest() {
return request;
}
public void setFirstRequest(CoapRequest request) {
this.request = request;
}
public CoapResponse getFirstResponse() {
return response;
}
public void setFirstResponse(CoapResponse response) {
this.response = response;
}
}
@Override
public void setTrigger(Object o) {
trigger = o;
}
@Override
public Object getTrigger() {
return trigger;
}
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/connection/BasicCoapClientChannel.java | Java | asf20 | 8,128 |
/* Copyright [2011] [University of Rostock]
*
* 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.
*****************************************************************************/
package org.ws4d.coap.connection;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.ws4d.coap.interfaces.CoapChannel;
import org.ws4d.coap.interfaces.CoapChannelManager;
import org.ws4d.coap.interfaces.CoapClient;
import org.ws4d.coap.interfaces.CoapClientChannel;
import org.ws4d.coap.interfaces.CoapMessage;
import org.ws4d.coap.interfaces.CoapServerChannel;
import org.ws4d.coap.interfaces.CoapSocketHandler;
import org.ws4d.coap.messages.AbstractCoapMessage;
import org.ws4d.coap.messages.CoapEmptyMessage;
import org.ws4d.coap.messages.CoapPacketType;
import org.ws4d.coap.tools.TimeoutHashMap;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
* @author Nico Laum <nico.laum@uni-rostock.de>
*/
public class BasicCoapSocketHandler implements CoapSocketHandler {
/* the socket handler has its own logger
* TODO: implement different socket handler for client and server channels */
private final static Logger logger = Logger.getLogger(BasicCoapSocketHandler.class);
protected WorkerThread workerThread = null;
protected HashMap<ChannelKey, CoapClientChannel> clientChannels = new HashMap<ChannelKey, CoapClientChannel>();
protected HashMap<ChannelKey, CoapServerChannel> serverChannels = new HashMap<ChannelKey, CoapServerChannel>();
private CoapChannelManager channelManager = null;
private DatagramChannel dgramChannel = null;
public static final int UDP_BUFFER_SIZE = 66000; // max UDP size = 65535
byte[] sendBuffer = new byte[UDP_BUFFER_SIZE];
private int localPort;
public BasicCoapSocketHandler(CoapChannelManager channelManager, int port) throws IOException {
logger.addAppender(new ConsoleAppender(new SimpleLayout()));
// ALL | DEBUG | INFO | WARN | ERROR | FATAL | OFF:
logger.setLevel(Level.WARN);
this.channelManager = channelManager;
dgramChannel = DatagramChannel.open();
dgramChannel.socket().bind(new InetSocketAddress(port)); //port can be 0, then a free port is chosen
this.localPort = dgramChannel.socket().getLocalPort();
dgramChannel.configureBlocking(false);
workerThread = new WorkerThread();
workerThread.start();
}
public BasicCoapSocketHandler(CoapChannelManager channelManager) throws IOException {
this(channelManager, 0);
}
protected class WorkerThread extends Thread {
Selector selector = null;
/* contains all received message keys of a remote (message id generated by the remote) to detect duplications */
TimeoutHashMap<MessageKey, Boolean> duplicateRemoteMap = new TimeoutHashMap<MessageKey, Boolean>(CoapMessage.ACK_RST_RETRANS_TIMEOUT_MS);
/* contains all received message keys of the host (message id generated by the host) to detect duplications */
TimeoutHashMap<Integer, Boolean> duplicateHostMap = new TimeoutHashMap<Integer, Boolean>(CoapMessage.ACK_RST_RETRANS_TIMEOUT_MS);
/* contains all messages that (possibly) needs to be retransmitted (ACK, RST)*/
TimeoutHashMap<MessageKey, CoapMessage> retransMsgMap = new TimeoutHashMap<MessageKey, CoapMessage>(CoapMessage.ACK_RST_RETRANS_TIMEOUT_MS);
/* contains all messages that are not confirmed yet (CON),
* MessageID is always generated by Host and therefore unique */
TimeoutHashMap<Integer, CoapMessage> timeoutConMsgMap = new TimeoutHashMap<Integer, CoapMessage>(CoapMessage.ACK_RST_RETRANS_TIMEOUT_MS);
/* this queue handles the timeout objects in the right order*/
private PriorityQueue<TimeoutObject<Integer>> timeoutQueue = new PriorityQueue<TimeoutObject<Integer>>();
public ConcurrentLinkedQueue<CoapMessage> sendBuffer = new ConcurrentLinkedQueue<CoapMessage>();
/* Contains all sent messages sorted by message ID */
long startTime;
static final int POLLING_INTERVALL = 10000;
ByteBuffer dgramBuffer;
public WorkerThread() {
dgramBuffer = ByteBuffer.allocate(UDP_BUFFER_SIZE);
startTime = System.currentTimeMillis();
try {
selector = Selector.open();
dgramChannel.register(selector, SelectionKey.OP_READ);
} catch (IOException e1) {
e1.printStackTrace();
}
}
public void close() {
if (clientChannels != null)
clientChannels.clear();
if (serverChannels != null)
serverChannels.clear();
try {
dgramChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
/* TODO: wake up thread and kill it*/
}
@Override
public void run() {
logger.log(Level.INFO, "Receive Thread started.");
long waitFor = POLLING_INTERVALL;
InetSocketAddress addr = null;
while (dgramChannel != null) {
/* send all messages in the send buffer */
sendBufferedMessages();
/* handle incoming packets */
dgramBuffer.clear();
try {
addr = (InetSocketAddress) dgramChannel.receive(dgramBuffer);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (addr != null){
logger.log(Level.INFO, "handle incomming msg");
handleIncommingMessage(dgramBuffer, addr);
}
/* handle timeouts */
waitFor = handleTimeouts();
/* TODO: find a good strategy when to update the timeout maps */
duplicateRemoteMap.update();
duplicateHostMap.update();
retransMsgMap.update();
timeoutConMsgMap.update();
/* wait until
* 1. selector.wakeup() is called by sendMessage()
* 2. incomming packet
* 3. timeout */
try {
/*FIXME: don't make a select, when something is in the sendQueue, otherwise the packet will be sent after some delay
* move this check and the select to a critical section */
selector.select(waitFor);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
protected synchronized void addMessageToSendBuffer(CoapMessage msg){
sendBuffer.add(msg);
/* send immediately */
selector.wakeup();
}
private void sendBufferedMessages(){
CoapMessage msg = sendBuffer.poll();
while(msg != null){
sendUdpMsg(msg);
msg = sendBuffer.poll();
}
}
private void handleIncommingMessage(ByteBuffer buffer, InetSocketAddress addr) {
CoapMessage msg;
try {
msg = AbstractCoapMessage.parseMessage(buffer.array(), buffer.position());
} catch (Exception e) {
logger.warn("Received invalid message: message dropped!");
e.printStackTrace();
return;
}
CoapPacketType packetType = msg.getPacketType();
int msgId = msg.getMessageID();
MessageKey msgKey = new MessageKey(msgId, addr.getAddress(), addr.getPort());
if (msg.isRequest()){
/* --- INCOMING REQUEST: This is an incoming client request with a message key generated by the remote client*/
if (packetType == CoapPacketType.ACK || packetType == CoapPacketType.RST){
logger.warn("Invalid Packet Type: Request can not be in a ACK or a RST packet");
return;
}
/* check for duplicates and retransmit the response if a duplication is detected */
if (isRemoteDuplicate(msgKey)){
retransmitRemoteDuplicate(msgKey);
return;
}
/* find or create server channel and handle incoming message */
CoapServerChannel channel = serverChannels.get(new ChannelKey(addr.getAddress(), addr.getPort()));
if (channel == null){
/*no server channel found -> create*/
channel = channelManager.createServerChannel(BasicCoapSocketHandler.this, msg, addr.getAddress(), addr.getPort());
if (channel != null){
/* add the new channel to the channel map */
addServerChannel(channel);
logger.info("Created new server channel.");
} else {
/* create failed -> server doesn't accept the connection --> send RST*/
CoapChannel fakeChannel = new BasicCoapServerChannel(BasicCoapSocketHandler.this, null, addr.getAddress(), addr.getPort());
CoapEmptyMessage rstMsg = new CoapEmptyMessage(CoapPacketType.RST, msgId);
rstMsg.setChannel(fakeChannel);
sendMessage(rstMsg);
return;
}
}
msg.setChannel(channel);
channel.handleMessage(msg);
return;
} else if (msg.isResponse()){
/* --- INCOMING RESPONSE: This is an incoming server response (message ID generated by host)
* or a separate server response (message ID generated by remote)*/
if (packetType == CoapPacketType.RST){
logger.warn("Invalid Packet Type: RST packet must be empty");
return;
}
/* check for separate response */
if (packetType == CoapPacketType.CON){
/* This is a separate response, the message ID is generated by the remote */
if (isRemoteDuplicate(msgKey)){
retransmitRemoteDuplicate(msgKey);
return;
}
/* This is a separate Response */
CoapClientChannel channel = clientChannels.get(new ChannelKey(addr.getAddress(), addr.getPort()));
if (channel == null){
logger.warn("Could not find channel of incomming separat response: message dropped");
return;
}
msg.setChannel(channel);
channel.handleMessage(msg);
return;
}
/* normal response (ACK or NON), message id was generated by host */
if (isHostDuplicate(msgId)){
/* drop duplicate responses */
return;
}
/* confirm the request*/
/* confirm message by removing it from the non confirmedMsgMap*/
/* Corresponding to the spec the server should be aware of a NON as answer to a CON*/
timeoutConMsgMap.remove(msgId);
CoapClientChannel channel = clientChannels.get(new ChannelKey(addr.getAddress(), addr.getPort()));
if (channel == null){
logger.warn("Could not find channel of incomming response: message dropped");
return;
}
msg.setChannel(channel);
channel.handleMessage(msg);
return;
} else if (msg.isEmpty()){
if (packetType == CoapPacketType.CON || packetType == CoapPacketType.NON){
/* TODO: is this always true? */
logger.warn("Invalid Packet Type: CON or NON packets cannot be empty");
return;
}
/* ACK or RST, Message Id was generated by the host*/
if (isHostDuplicate(msgId)){
/* drop duplicate responses */
return;
}
/* confirm */
timeoutConMsgMap.remove(msgId);
/* get channel */
/* This can be an ACK/RST for a client or a server channel */
CoapChannel channel = clientChannels.get(new ChannelKey(addr.getAddress(), addr.getPort()));
if (channel == null){
channel = serverChannels.get(new ChannelKey(addr.getAddress(), addr.getPort()));
}
if (channel == null){
logger.warn("Could not find channel of incomming response: message dropped");
return;
}
msg.setChannel(channel);
if (packetType == CoapPacketType.ACK ){
/* separate response ACK */
channel.handleMessage(msg);
return;
}
if (packetType == CoapPacketType.RST ){
/* connection closed by remote */
channel.handleMessage(msg);
return;
}
} else {
logger.error("Invalid Message Type: not a request, not a response, not empty");
}
}
private long handleTimeouts(){
long nextTimeout = POLLING_INTERVALL;
while (true){
TimeoutObject<Integer> tObj = timeoutQueue.peek();
if (tObj == null){
/* timeout queue is empty */
nextTimeout = POLLING_INTERVALL;
break;
}
nextTimeout = tObj.expires - System.currentTimeMillis();
if (nextTimeout > 0){
/* timeout not expired */
break;
}
/* timeout expired, sendMessage will send the message and create a new timeout
* if the message was already confirmed, nonConfirmedMsgMap.get() will return null */
timeoutQueue.poll();
Integer msgId = tObj.object;
/* retransmit message after expired timeout*/
sendUdpMsg((CoapMessage) timeoutConMsgMap.get(msgId));
}
return nextTimeout;
}
private boolean isRemoteDuplicate(MessageKey msgKey){
if (duplicateRemoteMap.get(msgKey) != null){
logger.info("Detected duplicate message");
return true;
}
return false;
}
private void retransmitRemoteDuplicate(MessageKey msgKey){
CoapMessage retransMsg = (CoapMessage) retransMsgMap.get(msgKey);
if (retransMsg == null){
logger.warn("Detected duplicate message but no response could be found");
} else {
sendUdpMsg(retransMsg);
}
}
private boolean isHostDuplicate(int msgId){
if (duplicateHostMap.get(msgId) != null){
logger.info("Detected duplicate message");
return true;
}
return false;
}
private void sendUdpMsg(CoapMessage msg) {
if (msg == null){
return;
}
CoapPacketType packetType = msg.getPacketType();
InetAddress inetAddr = msg.getChannel().getRemoteAddress();
int port = msg.getChannel().getRemotePort();
int msgId = msg.getMessageID();
if (packetType == CoapPacketType.CON){
/* in case of a CON this is a Request
* requests must be added to the timeout queue
* except this was the last retransmission */
if(msg.maxRetransReached()){
/* the connection is broken */
timeoutConMsgMap.remove(msgId);
msg.getChannel().lostConnection(true, false);
return;
}
msg.incRetransCounterAndTimeout();
timeoutConMsgMap.put(msgId, msg);
TimeoutObject<Integer> tObj = new TimeoutObject<Integer>(msgId, msg.getTimeout() + System.currentTimeMillis());
timeoutQueue.add(tObj);
}
if (packetType == CoapPacketType.ACK || packetType == CoapPacketType.RST){
/* save this type of messages for a possible retransmission */
retransMsgMap.put(new MessageKey(msgId, inetAddr, port), msg);
}
/* Nothing to do for NON*/
/* send message*/
ByteBuffer buf = ByteBuffer.wrap(msg.serialize());
/*TODO: check if serialization could fail... then do not put it to any Map!*/
try {
dgramChannel.send(buf, new InetSocketAddress(inetAddr, port));
logger.log(Level.INFO, "Send Msg with ID: " + msg.getMessageID());
} catch (IOException e) {
e.printStackTrace();
logger.error("Send UDP message failed");
}
}
}
private class MessageKey{
public int msgID;
public InetAddress inetAddr;
public int port;
public MessageKey(int msgID, InetAddress inetAddr, int port) {
super();
this.msgID = msgID;
this.inetAddr = inetAddr;
this.port = port;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result
+ ((inetAddr == null) ? 0 : inetAddr.hashCode());
result = prime * result + msgID;
result = prime * result + port;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MessageKey other = (MessageKey) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (inetAddr == null) {
if (other.inetAddr != null)
return false;
} else if (!inetAddr.equals(other.inetAddr))
return false;
if (msgID != other.msgID)
return false;
if (port != other.port)
return false;
return true;
}
private BasicCoapSocketHandler getOuterType() {
return BasicCoapSocketHandler.this;
}
}
private class TimeoutObject<T> implements Comparable<TimeoutObject>{
private long expires;
private T object;
public TimeoutObject(T object, long expires) {
this.expires = expires;
this.object = object;
}
public T getObject() {
return object;
}
public int compareTo(TimeoutObject o){
return (int) (this.expires - o.expires);
}
}
private void addClientChannel(CoapClientChannel channel) {
clientChannels.put(new ChannelKey(channel.getRemoteAddress(), channel.getRemotePort()), channel);
}
private void addServerChannel(CoapServerChannel channel) {
serverChannels.put(new ChannelKey(channel.getRemoteAddress(), channel.getRemotePort()), channel);
}
@Override
public int getLocalPort() {
return localPort;
}
@Override
public void removeClientChannel(CoapClientChannel channel) {
clientChannels.remove(new ChannelKey(channel.getRemoteAddress(), channel.getRemotePort()));
}
@Override
public void removeServerChannel(CoapServerChannel channel) {
serverChannels.remove(new ChannelKey(channel.getRemoteAddress(), channel.getRemotePort()));
}
@Override
public void close() {
workerThread.close();
}
@Override
public void sendMessage(CoapMessage message) {
if (workerThread != null) {
workerThread.addMessageToSendBuffer(message);
}
}
@Override
public CoapClientChannel connect(CoapClient client, InetAddress remoteAddress,
int remotePort) {
if (client == null){
return null;
}
if (clientChannels.containsKey(new ChannelKey(remoteAddress, remotePort))){
/* channel already exists */
logger.warn("Cannot connect: Client channel already exists");
return null;
}
CoapClientChannel channel = new BasicCoapClientChannel(this, client, remoteAddress, remotePort);
addClientChannel(channel);
return channel;
}
@Override
public CoapChannelManager getChannelManager() {
return this.channelManager;
}
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/connection/BasicCoapSocketHandler.java | Java | asf20 | 18,830 |
/* Copyright [2011] [University of Rostock]
*
* 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.
*****************************************************************************/
package org.ws4d.coap.connection;
import java.net.InetAddress;
import org.ws4d.coap.interfaces.CoapChannel;
import org.ws4d.coap.interfaces.CoapMessage;
import org.ws4d.coap.interfaces.CoapRequest;
import org.ws4d.coap.interfaces.CoapResponse;
import org.ws4d.coap.interfaces.CoapServer;
import org.ws4d.coap.interfaces.CoapServerChannel;
import org.ws4d.coap.interfaces.CoapSocketHandler;
import org.ws4d.coap.messages.BasicCoapRequest;
import org.ws4d.coap.messages.BasicCoapResponse;
import org.ws4d.coap.messages.CoapEmptyMessage;
import org.ws4d.coap.messages.CoapMediaType;
import org.ws4d.coap.messages.CoapPacketType;
import org.ws4d.coap.messages.CoapResponseCode;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
public class BasicCoapServerChannel extends BasicCoapChannel implements CoapServerChannel{
CoapServer server = null;
public BasicCoapServerChannel(CoapSocketHandler socketHandler,
CoapServer server, InetAddress remoteAddress,
int remotePort) {
super(socketHandler, remoteAddress, remotePort);
this.server = server;
}
@Override
public void close() {
socketHandler.removeServerChannel(this);
}
@Override
public void handleMessage(CoapMessage message) {
/* message MUST be a request */
if (message.isEmpty()){
return;
}
if (!message.isRequest()){
return;
//throw new IllegalStateException("Incomming server message is not a request");
}
BasicCoapRequest request = (BasicCoapRequest) message;
CoapChannel channel = request.getChannel();
/* TODO make this cast safe */
server.onRequest((CoapServerChannel) channel, request);
}
/*TODO: implement */
public void lostConnection(boolean notReachable, boolean resetByServer){
server.onSeparateResponseFailed(this);
}
@Override
public BasicCoapResponse createResponse(CoapMessage request, CoapResponseCode responseCode) {
return createResponse(request, responseCode, null);
}
@Override
public BasicCoapResponse createResponse(CoapMessage request, CoapResponseCode responseCode, CoapMediaType contentType){
BasicCoapResponse response;
if (request.getPacketType() == CoapPacketType.CON) {
response = new BasicCoapResponse(CoapPacketType.ACK, responseCode, request.getMessageID(), request.getToken());
} else if (request.getPacketType() == CoapPacketType.NON) {
response = new BasicCoapResponse(CoapPacketType.NON, responseCode, request.getMessageID(), request.getToken());
} else {
throw new IllegalStateException("Create Response failed, Request is neither a CON nor a NON packet");
}
if (contentType != null && contentType != CoapMediaType.UNKNOWN){
response.setContentType(contentType);
}
response.setChannel(this);
return response;
}
@Override
public CoapResponse createSeparateResponse(CoapRequest request, CoapResponseCode responseCode) {
BasicCoapResponse response = null;
if (request.getPacketType() == CoapPacketType.CON) {
/* The separate Response is CON (normally a Response is ACK or NON) */
response = new BasicCoapResponse(CoapPacketType.CON, responseCode, channelManager.getNewMessageID(), request.getToken());
/*send ack immediately */
sendMessage(new CoapEmptyMessage(CoapPacketType.ACK, request.getMessageID()));
} else if (request.getPacketType() == CoapPacketType.NON){
/* Just a normal response*/
response = new BasicCoapResponse(CoapPacketType.NON, responseCode, request.getMessageID(), request.getToken());
} else {
throw new IllegalStateException("Create Response failed, Request is neither a CON nor a NON packet");
}
response.setChannel(this);
return response;
}
@Override
public void sendSeparateResponse(CoapResponse response) {
sendMessage(response);
}
@Override
public CoapResponse createNotification(CoapRequest request, CoapResponseCode responseCode, int sequenceNumber){
/*use the packet type of the request: if con than con otherwise non*/
if (request.getPacketType() == CoapPacketType.CON){
return createNotification(request, responseCode, sequenceNumber, true);
} else {
return createNotification(request, responseCode, sequenceNumber, false);
}
}
@Override
public CoapResponse createNotification(CoapRequest request, CoapResponseCode responseCode, int sequenceNumber, boolean reliable){
BasicCoapResponse response = null;
CoapPacketType packetType;
if (reliable){
packetType = CoapPacketType.CON;
} else {
packetType = CoapPacketType.NON;
}
response = new BasicCoapResponse(packetType, responseCode, channelManager.getNewMessageID(), request.getToken());
response.setChannel(this);
response.setObserveOption(sequenceNumber);
return response;
}
@Override
public void sendNotification(CoapResponse response) {
sendMessage(response);
}
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/connection/BasicCoapServerChannel.java | Java | asf20 | 5,559 |
package org.ws4d.coap.tools;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class TimeoutHashMap<K, V> extends HashMap<Object, Object>{
private static final long serialVersionUID = 4987370276778256858L;
/* chronological list to remove expired elements when update() is called */
LinkedList<TimoutType<K>> timeoutQueue = new LinkedList<TimoutType<K>>();
/* Default Timeout is one minute */
long timeout = 60000;
public TimeoutHashMap(long timeout){
this.timeout = timeout;
}
@Override
public Object put(Object key, Object value) {
long expires = System.currentTimeMillis() + timeout;
TimoutType<V> timeoutValue = new TimoutType<V>((V) value, expires);
TimoutType<K> timeoutKey = new TimoutType<K>((K) key, expires);
timeoutQueue.add(timeoutKey);
timeoutValue = (TimoutType<V>) super.put((K) key, timeoutValue);
if (timeoutValue != null){
return timeoutValue.object;
}
return null;
}
@Override
public Object get(Object key) {
TimoutType<V> timeoutValue = (TimoutType<V>) super.get(key);
if (timeoutValueIsValid(timeoutValue)){
return timeoutValue.object;
}
return null;
}
@Override
public Object remove(Object key) {
TimoutType<V> timeoutValue = (TimoutType<V>) super.remove(key);
if (timeoutValueIsValid(timeoutValue)){
return timeoutValue.object;
}
return null;
}
@Override
public void clear() {
super.clear();
timeoutQueue.clear();
}
/* remove expired elements */
public void update(){
while(true) {
TimoutType<K> timeoutKey = timeoutQueue.peek();
if (timeoutKey == null){
/* if the timeoutKey queue is empty, there must be no more elements in the hashmap
* otherwise there is a bug in the implementation */
if (!super.isEmpty()){
throw new IllegalStateException("Error in TimeoutHashMap. Timeout queue is empty but hashmap not!");
}
return;
}
long now = System.currentTimeMillis();
if (now > timeoutKey.expires){
timeoutQueue.poll();
TimoutType<V> timeoutValue = (TimoutType<V>) super.remove(timeoutKey.object);
if (timeoutValueIsValid(timeoutValue)){
/* This is a very special case which happens if an entry is overridden:
* - put V with K
* - put V2 with K
* - K is expired but V2 not
* because this is expected to be happened very seldom, we "reput" V2 to the hashmap
* wich is better than every time to making a get and than a remove */
super.put(timeoutKey.object, timeoutValue);
}
} else {
/* Key is not expired -> break the loop */
break;
}
}
}
@Override
public Object clone() {
// TODO implement function
throw new IllegalStateException();
// return super.clone();
}
@Override
public boolean containsKey(Object arg0) {
// TODO implement function
throw new IllegalStateException();
// return super.containsKey(arg0);
}
@Override
public boolean containsValue(Object arg0) {
// TODO implement function
throw new IllegalStateException();
// return super.containsValue(arg0);
}
@Override
public Set<Entry<Object, Object>> entrySet() {
// TODO implement function
throw new IllegalStateException();
// return super.entrySet();
}
@Override
public boolean isEmpty() {
// TODO implement function
throw new IllegalStateException();
// return super.isEmpty();
}
@Override
public Set<Object> keySet() {
// TODO implement function
throw new IllegalStateException();
// return super.keySet();
}
@Override
public void putAll(Map<? extends Object, ? extends Object> arg0) {
// TODO implement function
throw new IllegalStateException();
// super.putAll(arg0);
}
@Override
public int size() {
// TODO implement function
throw new IllegalStateException();
// return super.size();
}
@Override
public Collection<Object> values() {
// TODO implement function
throw new IllegalStateException();
// return super.values();
}
/* private classes and methods */
private boolean timeoutValueIsValid(TimoutType<V> timeoutValue){
return timeoutValue != null && System.currentTimeMillis() < timeoutValue.expires;
}
private class TimoutType<T>{
public T object;
public long expires;
public TimoutType(T object, long expires) {
super();
this.object = object;
this.expires = expires;
}
}
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/tools/TimeoutHashMap.java | Java | asf20 | 4,776 |
package org.ws4d.coap.messages;
import java.io.UnsupportedEncodingException;
import java.util.Vector;
import org.ws4d.coap.interfaces.CoapRequest;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
public class BasicCoapRequest extends AbstractCoapMessage implements CoapRequest {
CoapRequestCode requestCode;
public BasicCoapRequest(byte[] bytes, int length) {
/* length ought to be provided by UDP header */
this(bytes, length, 0);
}
public BasicCoapRequest(byte[] bytes, int length, int offset) {
serialize(bytes, length, offset);
/* check if request code is valid, this function throws an error in case of an invalid argument */
requestCode = CoapRequestCode.parseRequestCode(this.messageCodeValue);
//TODO: check integrity of header options
}
public BasicCoapRequest(CoapPacketType packetType, CoapRequestCode requestCode, int messageId) {
this.version = 1;
this.packetType = packetType;
this.requestCode = requestCode;
this.messageCodeValue = requestCode.getValue();
this.messageId = messageId;
}
@Override
public void setToken(byte[] token){
/* this function is only public for a request*/
super.setToken(token);
}
@Override
public CoapRequestCode getRequestCode() {
return requestCode;
}
@Override
public void setUriHost(String host) {
if (host == null) return;
if (options.optionExists(CoapHeaderOptionType.Uri_Host)){
throw new IllegalArgumentException("Uri-Host option already exists");
}
if (host.length() < 1 || host.length() > CoapHeaderOption.MAX_LENGTH){
throw new IllegalArgumentException("Invalid Uri-Host option length");
}
/*TODO: check if host is a valid address */
options.addOption(CoapHeaderOptionType.Uri_Host, host.getBytes());
}
@Override
public void setUriPort(int port) {
if (port < 0) return;
if (options.optionExists(CoapHeaderOptionType.Uri_Port)){
throw new IllegalArgumentException("Uri-Port option already exists");
}
byte[] value = long2CoapUint(port);
if(value.length < 0 || value.length > 2){
throw new IllegalStateException("Illegal Uri-Port length");
}
options.addOption(new CoapHeaderOption(CoapHeaderOptionType.Uri_Port, value));
}
@Override
public void setUriPath(String path) {
if (path == null) return;
if (path.length() > CoapHeaderOption.MAX_LENGTH ){
throw new IllegalArgumentException("Uri-Path option too long");
}
/* delete old options if present */
options.removeOption(CoapHeaderOptionType.Uri_Path);
/*create substrings */
String[] pathElements = path.split("/");
/* add a Uri Path option for each part */
for (String element : pathElements) {
/* check length */
if(element.length() < 0 || element.length() > CoapHeaderOption.MAX_LENGTH){
throw new IllegalArgumentException("Invalid Uri-Path");
} else if (element.length() > 0){
/* ignore empty substrings */
options.addOption(CoapHeaderOptionType.Uri_Path, element.getBytes());
}
}
}
@Override
public void setUriQuery(String query) {
if (query == null) return;
if (query.length() > CoapHeaderOption.MAX_LENGTH ){
throw new IllegalArgumentException("Uri-Query option too long");
}
/* delete old options if present */
options.removeOption(CoapHeaderOptionType.Uri_Query);
/*create substrings */
String[] pathElements = query.split("&");
/* add a Uri Path option for each part */
for (String element : pathElements) {
/* check length */
if(element.length() < 0 || element.length() > CoapHeaderOption.MAX_LENGTH){
throw new IllegalArgumentException("Invalid Uri-Path");
} else if (element.length() > 0){
/* ignore empty substrings */
options.addOption(CoapHeaderOptionType.Uri_Query, element.getBytes());
}
}
}
@Override
public void setProxyUri(String proxyUri) {
if (proxyUri == null) return;
if (options.optionExists(CoapHeaderOptionType.Proxy_Uri)){
throw new IllegalArgumentException("Proxy Uri already exists");
}
if (proxyUri.length() < 1){
throw new IllegalArgumentException("Proxy Uri must be at least one byte long");
}
if (proxyUri.length() > CoapHeaderOption.MAX_LENGTH ){
throw new IllegalArgumentException("Proxy Uri longer then 270 bytes are not supported yet (to be implemented)");
}
options.addOption(CoapHeaderOptionType.Proxy_Uri, proxyUri.getBytes());
}
@Override
public Vector<String> getUriQuery(){
Vector<String> queryList = new Vector<String>();
for (CoapHeaderOption option : options) {
if(option.getOptionType() == CoapHeaderOptionType.Uri_Query){
queryList.add(new String(option.getOptionData()));
}
}
return queryList;
}
@Override
public String getUriHost(){
return new String(options.getOption(CoapHeaderOptionType.Uri_Host).getOptionData());
}
@Override
public int getUriPort(){
CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Uri_Port);
if (option == null){
return -1; //TODO: return default Coap Port?
}
byte[] value = option.getOptionData();
if(value.length < 0 || value.length > 2){
/* should never happen because this is an internal variable and should be checked during serialization */
throw new IllegalStateException("Illegal Uri-Port Option length");
}
/* checked length -> cast is safe*/
return (int)coapUint2Long(options.getOption(CoapHeaderOptionType.Uri_Port).getOptionData());
}
@Override
public String getUriPath() {
if (options.getOption(CoapHeaderOptionType.Uri_Path) == null){
return null;
}
StringBuilder uriPathBuilder = new StringBuilder();
for (CoapHeaderOption option : options) {
if (option.getOptionType() == CoapHeaderOptionType.Uri_Path) {
String uriPathElement;
try {
uriPathElement = new String(option.getOptionData(), "UTF-8");
uriPathBuilder.append("/");
uriPathBuilder.append(uriPathElement);
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("Invalid Encoding");
}
}
}
return uriPathBuilder.toString();
}
@Override
public void addAccept(CoapMediaType mediaType){
options.addOption(CoapHeaderOptionType.Accept, long2CoapUint(mediaType.getValue()));
}
@Override
public Vector<CoapMediaType> getAccept(CoapMediaType mediaType){
if (options.getOption(CoapHeaderOptionType.Accept) == null){
return null;
}
Vector<CoapMediaType> acceptList = new Vector<CoapMediaType>();
for (CoapHeaderOption option : options) {
if (option.getOptionType() == CoapHeaderOptionType.Accept) {
CoapMediaType accept = CoapMediaType.parse((int)coapUint2Long(option.optionData));
// if (accept != CoapMediaType.UNKNOWN){
/* add also UNKNOWN types to list */
acceptList.add(accept);
// }
}
}
return acceptList;
}
@Override
public String getProxyUri(){
CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Proxy_Uri);
if (option == null)
return null;
return new String(option.getOptionData());
}
@Override
public void addETag(byte[] etag) {
if (etag == null){
throw new IllegalArgumentException("etag MUST NOT be null");
}
if (etag.length < 1 || etag.length > 8){
throw new IllegalArgumentException("Invalid etag length");
}
options.addOption(CoapHeaderOptionType.Etag, etag);
}
@Override
public Vector<byte[]> getETag() {
if (options.getOption(CoapHeaderOptionType.Etag) == null){
return null;
}
Vector<byte[]> etagList = new Vector<byte[]>();
for (CoapHeaderOption option : options) {
if (option.getOptionType() == CoapHeaderOptionType.Etag) {
byte[] data = option.getOptionData();
if (data.length >= 1 && data.length <= 8){
etagList.add(option.getOptionData());
}
}
}
return etagList;
}
@Override
public boolean isRequest() {
return true;
}
@Override
public boolean isResponse() {
return false;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public String toString() {
return packetType.toString() + ", " + requestCode.toString() + ", MsgId: " + getMessageID() +", #Options: " + options.getOptionCount();
}
@Override
public void setRequestCode(CoapRequestCode requestCode) {
this.requestCode = requestCode;
}
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/messages/BasicCoapRequest.java | Java | asf20 | 8,398 |
package org.ws4d.coap.messages;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
public enum CoapResponseCode {
Created_201(65),
Deleted_202(66),
Valid_203(67),
Changed_204(68),
Content_205(69),
Bad_Request_400(128),
Unauthorized_401(129),
Bad_Option_402(130),
Forbidden_403(131),
Not_Found_404(132),
Method_Not_Allowed_405(133),
Precondition_Failed_412(140),
Request_Entity_To_Large_413(141),
Unsupported_Media_Type_415(143),
Internal_Server_Error_500(160),
Not_Implemented_501(161),
Bad_Gateway_502(162),
Service_Unavailable_503(163),
Gateway_Timeout_504(164),
Proxying_Not_Supported_505(165),
UNKNOWN(-1);
private int code;
private CoapResponseCode(int code) {
this.code = code;
}
public static CoapResponseCode parseResponseCode(int codeValue) {
switch (codeValue) {
/* 32..63: reserved */
/* 64 is not used anymore */
// case 64:
// this.code = ResponseCode.OK_200;
// break;
case 65: return Created_201;
case 66: return Deleted_202;
case 67: return Valid_203;
case 68: return Changed_204;
case 69: return Content_205;
case 128: return Bad_Request_400;
case 129: return Unauthorized_401;
case 130: return Bad_Option_402;
case 131: return Forbidden_403;
case 132: return Not_Found_404;
case 133: return Method_Not_Allowed_405;
case 140: return Precondition_Failed_412;
case 141: return Request_Entity_To_Large_413;
case 143: return Unsupported_Media_Type_415;
case 160: return Internal_Server_Error_500;
case 161: return Not_Implemented_501;
case 162: return Bad_Gateway_502;
case 163: return Service_Unavailable_503;
case 164: return Gateway_Timeout_504;
case 165: return Proxying_Not_Supported_505;
default:
if (codeValue >= 64 && codeValue <= 191) {
return UNKNOWN;
} else {
throw new IllegalArgumentException("Invalid Response Code");
}
}
}
public int getValue() {
return code;
}
@Override
public String toString() {
switch (this) {
case Created_201:
return "Created_201";
case Deleted_202:
return "Deleted_202";
case Valid_203:
return "Valid_203";
case Changed_204:
return "Changed_204";
case Content_205:
return "Content_205";
case Bad_Request_400:
return "Bad_Request_400";
case Unauthorized_401:
return "Unauthorized_401";
case Bad_Option_402:
return "Bad_Option_402";
case Forbidden_403:
return "Forbidden_403";
case Not_Found_404:
return "Not_Found_404";
case Method_Not_Allowed_405:
return "Method_Not_Allowed_405";
case Precondition_Failed_412:
return "Precondition_Failed_412";
case Request_Entity_To_Large_413:
return "Request_Entity_To_Large_413";
case Unsupported_Media_Type_415:
return "Unsupported_Media_Type_415";
case Internal_Server_Error_500:
return "Internal_Server_Error_500";
case Not_Implemented_501:
return "Not_Implemented_501";
case Bad_Gateway_502:
return "Bad_Gateway_502";
case Service_Unavailable_503:
return "Service_Unavailable_503";
case Gateway_Timeout_504:
return "Gateway_Timeout_504";
case Proxying_Not_Supported_505:
return "Proxying_Not_Supported_505";
default:
return "Unknown_Response_Code";
}
}
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/messages/CoapResponseCode.java | Java | asf20 | 3,339 |
package org.ws4d.coap.messages;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
public class CoapBlockOption{
private int number;
private boolean more;
private CoapBlockSize blockSize;
public CoapBlockOption(byte[] data){
if (data.length <1 || data.length > 3){
throw new IllegalArgumentException("invalid block option");
}
long val = AbstractCoapMessage.coapUint2Long(data);
this.blockSize = CoapBlockSize.parse((int) (val & 0x7));
if (blockSize == null){
throw new IllegalArgumentException("invalid block options");
}
if ((val & 0x8) == 0){
//more bit not set
more = false;
} else {
more = true;
}
number = (int) (val >> 4);
}
public CoapBlockOption(int number, boolean more, CoapBlockSize blockSize){
if (blockSize == null){
throw new IllegalArgumentException();
}
if (number < 0 || number > 0xFFFFFF ){
//not an unsigned 20 bit value
throw new IllegalArgumentException();
}
this.blockSize = blockSize;
this.number = number;
this.more = more;
}
public int getNumber() {
return number;
}
public boolean isLast() {
return !more;
}
public CoapBlockSize getBlockSize() {
return blockSize;
}
public int getBytePosition(){
return number << (blockSize.getExponent() + 4);
}
public byte[] getBytes(){
int value = number << 4;
value |= blockSize.getExponent();
if (more){
value |= 0x8;
}
return AbstractCoapMessage.long2CoapUint(value);
}
public enum CoapBlockSize {
BLOCK_16 (0),
BLOCK_32 (1),
BLOCK_64 (2),
BLOCK_128(3),
BLOCK_256 (4),
BLOCK_512 (5),
BLOCK_1024 (6);
int exp;
CoapBlockSize(int exponent){
exp = exponent;
}
public static CoapBlockSize parse(int exponent){
switch(exponent){
case 0: return BLOCK_16;
case 1: return BLOCK_32;
case 2: return BLOCK_64;
case 3: return BLOCK_128;
case 4: return BLOCK_256;
case 5: return BLOCK_512;
case 6: return BLOCK_1024;
default : return null;
}
}
public int getExponent(){
return exp;
}
public int getSize(){
return 1 << (exp+4);
}
}
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/messages/CoapBlockOption.java | Java | asf20 | 2,341 |
/* Copyright [2011] [University of Rostock]
*
* 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.
*****************************************************************************/
package org.ws4d.coap.messages;
/**
* Type-safe class for CoapPacketTypes
*
* @author Nico Laum <nico.laum@uni-rostock.de>
* @author Sebastian Unger <sebastian.unger@uni-rostock.de>
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
public enum CoapPacketType {
CON(0x00),
NON(0x01),
ACK(0x02),
RST(0x03);
private int packetType;
CoapPacketType(int packetType) {
if (packetType >= 0x00 && packetType <= 0x03){
this.packetType = packetType;
} else {
throw new IllegalStateException("Unknown CoAP Packet Type");
}
}
public static CoapPacketType getPacketType(int packetType) {
if (packetType == 0x00)
return CON;
else if (packetType == 0x01)
return NON;
else if (packetType == 0x02)
return ACK;
else if (packetType == 0x03)
return RST;
else
throw new IllegalStateException("Unknown CoAP Packet Type");
}
public int getValue() {
return packetType;
}
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/messages/CoapPacketType.java | Java | asf20 | 1,739 |
/* Copyright [2011] [University of Rostock]
*
* 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.
*****************************************************************************/
/* WS4D Java CoAP Implementation
* (c) 2011 WS4D.org
*
* written by Sebastian Unger
*/
package org.ws4d.coap.messages;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.Iterator;
import java.util.Random;
import java.util.Vector;
import org.apache.log4j.Logger;
import org.ws4d.coap.connection.BasicCoapChannelManager;
import org.ws4d.coap.interfaces.CoapChannel;
import org.ws4d.coap.interfaces.CoapMessage;
/**
* @author Christian Lerche <christian.lerche@uni-rostock.de>
*/
public abstract class AbstractCoapMessage implements CoapMessage {
/* use the logger of the channel manager */
private final static Logger logger = Logger.getLogger(BasicCoapChannelManager.class);
protected static final int HEADER_LENGTH = 4;
/* Header */
protected int version;
protected CoapPacketType packetType;
protected int messageCodeValue;
//protected int optionCount;
protected int messageId;
/* Options */
protected CoapHeaderOptions options = new CoapHeaderOptions();
/* Payload */
protected byte[] payload = null;
protected int payloadLength = 0;
/* corresponding channel */
CoapChannel channel = null;
/* Retransmission State */
int timeout = 0;
int retransmissionCounter = 0;
protected void serialize(byte[] bytes, int length, int offset){
/* check length to avoid buffer overflow exceptions */
this.version = 1;
this.packetType = (CoapPacketType.getPacketType((bytes[offset + 0] & 0x30) >> 4));
int optionCount = bytes[offset + 0] & 0x0F;
this.messageCodeValue = (bytes[offset + 1] & 0xFF);
this.messageId = ((bytes[offset + 2] << 8) & 0xFF00) + (bytes[offset + 3] & 0xFF);
/* serialize options */
this.options = new CoapHeaderOptions(bytes, offset + HEADER_LENGTH, optionCount);
/* get and check payload length */
payloadLength = length - HEADER_LENGTH - options.getDeserializedLength();
if (payloadLength < 0){
throw new IllegalStateException("Invaldid CoAP Message (payload length negative)");
}
/* copy payload */
int payloadOffset = offset + HEADER_LENGTH + options.getDeserializedLength();
payload = new byte[payloadLength];
for (int i = 0; i < payloadLength; i++){
payload[i] = bytes[i + payloadOffset];
}
}
/* TODO: this function should be in another class */
public static CoapMessage parseMessage(byte[] bytes, int length){
return parseMessage(bytes, length, 0);
}
public static CoapMessage parseMessage(byte[] bytes, int length, int offset){
/* we "peek" the header to determine the kind of message
* TODO: duplicate Code */
int messageCodeValue = (bytes[offset + 1] & 0xFF);
if (messageCodeValue == 0){
return new CoapEmptyMessage(bytes, length, offset);
} else if (messageCodeValue >= 0 && messageCodeValue <= 31 ){
return new BasicCoapRequest(bytes, length, offset);
} else if (messageCodeValue >= 64 && messageCodeValue <= 191){
return new BasicCoapResponse(bytes, length, offset);
} else {
throw new IllegalArgumentException("unknown CoAP message");
}
}
public int getVersion() {
return version;
}
@Override
public int getMessageCodeValue() {
return messageCodeValue;
}
@Override
public CoapPacketType getPacketType() {
return packetType;
}
public byte[] getPayload() {
return payload;
}
public int getPayloadLength() {
return payloadLength;
}
@Override
public int getMessageID() {
return messageId;
}
@Override
public void setMessageID(int messageId) {
this.messageId = messageId;
}
public byte[] serialize() {
/* TODO improve memory allocation */
/* serialize header options first to get the length*/
int optionsLength = 0;
byte[] optionsArray = null;
if (options != null) {
optionsArray = this.options.serialize();
optionsLength = this.options.getSerializedLength();
}
/* allocate memory for the complete packet */
int length = HEADER_LENGTH + optionsLength + payloadLength;
byte[] serializedPacket = new byte[length];
/* serialize header */
serializedPacket[0] = (byte) ((this.version & 0x03) << 6);
serializedPacket[0] |= (byte) ((this.packetType.getValue() & 0x03) << 4);
serializedPacket[0] |= (byte) (options.getOptionCount() & 0x0F);
serializedPacket[1] = (byte) (this.getMessageCodeValue() & 0xFF);
serializedPacket[2] = (byte) ((this.messageId >> 8) & 0xFF);
serializedPacket[3] = (byte) (this.messageId & 0xFF);
/* copy serialized options to the final array */
int offset = HEADER_LENGTH;
if (options != null) {
for (int i = 0; i < optionsLength; i++)
serializedPacket[i + offset] = optionsArray[i];
}
/* copy payload to the final array */
offset = HEADER_LENGTH + optionsLength;
for (int i = 0; i < this.payloadLength; i++) {
serializedPacket[i + offset] = payload[i];
}
return serializedPacket;
}
public void setPayload(byte[] payload) {
this.payload = payload;
if (payload!=null)
this.payloadLength = payload.length;
else
this.payloadLength = 0;
}
public void setPayload(char[] payload) {
this.payload = new byte[payload.length];
for (int i = 0; i < payload.length; i++) {
this.payload[i] = (byte) payload[i];
}
this.payloadLength = payload.length;
}
public void setPayload(String payload) {
setPayload(payload.toCharArray());
}
@Override
public void setContentType(CoapMediaType mediaType){
CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Content_Type);
if (option != null){
/* content Type MUST only exists once */
throw new IllegalStateException("added content option twice");
}
if ( mediaType == CoapMediaType.UNKNOWN){
throw new IllegalStateException("unknown content type");
}
/* convert value */
byte[] data = long2CoapUint(mediaType.getValue());
/* no need to check result, mediaType is safe */
/* add option to Coap Header*/
options.addOption(new CoapHeaderOption(CoapHeaderOptionType.Content_Type, data));
}
@Override
public CoapMediaType getContentType(){
CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Content_Type);
if (option == null){
/* not content type TODO: return UNKNOWN ?*/
return null;
}
/* no need to check length, CoapMediaType parse function will do*/
int mediaTypeCode = (int) coapUint2Long(options.getOption(CoapHeaderOptionType.Content_Type).getOptionData());
return CoapMediaType.parse(mediaTypeCode);
}
@Override
public byte[] getToken(){
CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Token);
if (option == null){
return null;
}
return option.getOptionData();
}
protected void setToken(byte[] token){
if (token == null){
return;
}
if (token.length < 1 || token.length > 8){
throw new IllegalArgumentException("Invalid Token Length");
}
options.addOption(CoapHeaderOptionType.Token, token);
}
@Override
public CoapBlockOption getBlock1(){
CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Block1);
if (option == null){
return null;
}
CoapBlockOption blockOpt = new CoapBlockOption(option.getOptionData());
return blockOpt;
}
@Override
public void setBlock1(CoapBlockOption blockOption){
CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Block1);
if (option != null){
//option already exists
options.removeOption(CoapHeaderOptionType.Block1);
}
options.addOption(CoapHeaderOptionType.Block1, blockOption.getBytes());
}
@Override
public CoapBlockOption getBlock2(){
CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Block2);
if (option == null){
return null;
}
CoapBlockOption blockOpt = new CoapBlockOption(option.getOptionData());
return blockOpt;
}
@Override
public void setBlock2(CoapBlockOption blockOption){
CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Block2);
if (option != null){
//option already exists
options.removeOption(CoapHeaderOptionType.Block2);
}
options.addOption(CoapHeaderOptionType.Block2, blockOption.getBytes());
}
@Override
public Integer getObserveOption() {
CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Observe);
if (option == null){
return null;
}
byte[] data = option.getOptionData();
if (data.length < 0 || data.length > 2){
logger.warn("invalid observe option length, return null");
return null;
}
return (int) AbstractCoapMessage.coapUint2Long(data);
}
@Override
public void setObserveOption(int sequenceNumber) {
CoapHeaderOption option = options.getOption(CoapHeaderOptionType.Observe);
if (option != null){
options.removeOption(CoapHeaderOptionType.Observe);
}
byte[] data = long2CoapUint(sequenceNumber);
if (data.length < 0 || data.length > 2){
throw new IllegalArgumentException("invalid observe option length");
}
options.addOption(CoapHeaderOptionType.Observe, data);
}
public void copyHeaderOptions(AbstractCoapMessage origin){
options.removeAll();
options.copyFrom(origin.options);
}
public void removeOption(CoapHeaderOptionType optionType){
options.removeOption(optionType);
}
@Override
public CoapChannel getChannel() {
return channel;
}
@Override
public void setChannel(CoapChannel channel) {
this.channel = channel;
}
@Override
public int getTimeout() {
if (timeout == 0) {
Random random = new Random();
timeout = RESPONSE_TIMEOUT_MS
+ random.nextInt((int) (RESPONSE_TIMEOUT_MS * RESPONSE_RANDOM_FACTOR)
- RESPONSE_TIMEOUT_MS);
}
return timeout;
}
@Override
public boolean maxRetransReached() {
if (retransmissionCounter < MAX_RETRANSMIT) {
return false;
}
return true;
}
@Override
public void incRetransCounterAndTimeout() { /*TODO: Rename*/
retransmissionCounter += 1;
timeout *= 2;
}
@Override
public boolean isReliable() {
if (packetType == CoapPacketType.NON){
return false;
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((channel == null) ? 0 : channel.hashCode());
result = prime * result + getMessageID();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AbstractCoapMessage other = (AbstractCoapMessage) obj;
if (channel == null) {
if (other.channel != null)
return false;
} else if (!channel.equals(other.channel))
return false;
if (getMessageID() != other.getMessageID())
return false;
return true;
}
protected static long coapUint2Long(byte[] data){
/* avoid buffer overflow */
if(data.length > 8){
return -1;
}
/* fill with leading zeros */
byte[] tmp = new byte[8];
for (int i = 0; i < data.length; i++) {
tmp[i + 8 - data.length] = data[i];
}
/* convert to long */
ByteBuffer buf = ByteBuffer.wrap(tmp);
/* byte buffer contains 8 bytes */
return buf.getLong();
}
protected static byte[] long2CoapUint(long value){
/* only unsigned values supported */
if (value < 0){
return null;
}
/* a zero length value implies zero */
if (value == 0){
return new byte[0];
}
/* convert long to byte array with a fixed length of 8 byte*/
ByteBuffer buf = ByteBuffer.allocate(8);
buf.putLong(value);
byte[] tmp = buf.array();
/* remove leading zeros */
int leadingZeros = 0;
for (int i = 0; i < tmp.length; i++) {
if (tmp[i] == 0){
leadingZeros = i+1;
} else {
break;
}
}
/* copy to byte array without leading zeros */
byte[] result = new byte[8 - leadingZeros];
for (int i = 0; i < result.length; i++) {
result[i] = tmp[i + leadingZeros];
}
return result;
}
public enum CoapHeaderOptionType {
UNKNOWN(-1),
Content_Type (1),
Max_Age (2),
Proxy_Uri(3),
Etag (4),
Uri_Host (5),
Location_Path (6),
Uri_Port (7),
Location_Query (8),
Uri_Path (9),
Observe (10),
Token (11),
Accept (12),
If_Match (13),
Uri_Query (15),
If_None_Match (21),
Block1 (19),
Block2 (17);
int value;
CoapHeaderOptionType(int optionValue){
value = optionValue;
}
public static CoapHeaderOptionType parse(int optionTypeValue){
switch(optionTypeValue){
case 1: return Content_Type;
case 2: return Max_Age;
case 3: return Proxy_Uri;
case 4: return Etag;
case 5: return Uri_Host;
case 6: return Location_Path;
case 7: return Uri_Port;
case 8: return Location_Query;
case 9: return Uri_Path;
case 10: return Observe;
case 11:return Token;
case 12:return Accept;
case 13:return If_Match;
case 15:return Uri_Query;
case 21:return If_None_Match;
case 19:return Block1;
case 17:return Block2;
default: return UNKNOWN;
}
}
public int getValue(){
return value;
}
/* TODO: implement validity checks */
/*TODO: implement isCritical(int optionTypeValue), isElective()*/
}
protected class CoapHeaderOption implements Comparable<CoapHeaderOption> {
CoapHeaderOptionType optionType;
int optionTypeValue; /* integer representation of optionType*/
byte[] optionData;
int shortLength;
int longLength;
int deserializedLength;
static final int MAX_LENGTH = 270;
public int getDeserializedLength() {
return deserializedLength;
}
public CoapHeaderOption(CoapHeaderOptionType optionType, byte[] value) {
if (optionType == CoapHeaderOptionType.UNKNOWN){
/*TODO: implement check if it is a critical option */
throw new IllegalStateException("Unknown header option");
}
if (value == null){
throw new IllegalArgumentException("Header option value MUST NOT be null");
}
this.optionTypeValue = optionType.getValue();
this.optionData = value;
if (value.length < 15) {
shortLength = value.length;
longLength = 0;
} else {
shortLength = 15;
longLength = value.length - shortLength;
}
}
public CoapHeaderOption(byte[] bytes, int offset, int lastOptionNumber){
int headerLength;
/* parse option type */
optionTypeValue = ((bytes[offset] & 0xF0) >> 4) + lastOptionNumber;
optionType = CoapHeaderOptionType.parse(optionTypeValue);
if (optionType == CoapHeaderOptionType.UNKNOWN){
if (optionTypeValue % 14 == 0){
/* no-op: no operation for deltas > 14 */
} else {
/*TODO: implement check if it is a critical option */
throw new IllegalArgumentException("Unknown header option");
}
}
/* parse length */
if ((bytes[offset] & 0x0F) < 15) {
shortLength = bytes[offset] & 0x0F;
longLength = 0;
headerLength = 1;
} else {
shortLength = 15;
longLength = bytes[offset + 1];
headerLength = 2; /* additional length byte */
}
/* copy value */
optionData = new byte[shortLength + longLength];
for (int i = 0; i < shortLength + longLength; i++){
optionData[i] = bytes[i + headerLength + offset];
}
deserializedLength += headerLength + shortLength + longLength;
}
@Override
public int compareTo(CoapHeaderOption option) {
/* compare function for sorting
* TODO: check what happens in case of equal option values
* IMPORTANT: order must be the same for e.g., URI path*/
if (this.optionTypeValue != option.optionTypeValue)
return this.optionTypeValue < option.optionTypeValue ? -1 : 1;
else
return 0;
}
public boolean hasLongLength(){
if (shortLength == 15){
return true;
} else return false;
}
public int getLongLength() {
return longLength;
}
public int getShortLength() {
return shortLength;
}
public int getOptionTypeValue() {
return optionTypeValue;
}
public byte[] getOptionData() {
return optionData;
}
public int getSerializeLength(){
if (hasLongLength()){
return optionData.length + 2;
} else {
return optionData.length + 1;
}
}
@Override
public String toString() {
char[] printableOptionValue = new char[optionData.length];
for (int i = 0; i < optionData.length; i++)
printableOptionValue[i] = (char) optionData[i];
return "Option Number: "
+ " (" + optionTypeValue + ")"
+ ", Option Value: " + String.copyValueOf(printableOptionValue);
}
public CoapHeaderOptionType getOptionType() {
return optionType;
}
}
protected class CoapHeaderOptions implements Iterable<CoapHeaderOption>{
private Vector<CoapHeaderOption> headerOptions = new Vector<CoapHeaderOption>();
private int deserializedLength;
private int serializedLength = 0;
public CoapHeaderOptions(byte[] bytes, int option_count){
this(bytes, option_count, option_count);
}
public CoapHeaderOptions(byte[] bytes, int offset, int optionCount){
/* note: we only receive deltas and never concrete numbers */
/* TODO: check integrity */
deserializedLength = 0;
int lastOptionNumber = 0;
int optionOffset = offset;
for (int i = 0; i < optionCount; i++) {
CoapHeaderOption option = new CoapHeaderOption(bytes, optionOffset, lastOptionNumber);
lastOptionNumber = option.getOptionTypeValue();
deserializedLength += option.getDeserializedLength();
optionOffset += option.getDeserializedLength();
addOption(option);
}
}
public CoapHeaderOptions() {
/* creates empty header options */
}
public CoapHeaderOption getOption(int optionNumber) {
for (CoapHeaderOption headerOption : headerOptions) {
if (headerOption.getOptionTypeValue() == optionNumber) {
return headerOption;
}
}
return null;
}
public CoapHeaderOption getOption(CoapHeaderOptionType optionType) {
for (CoapHeaderOption headerOption : headerOptions) {
if (headerOption.getOptionType() == optionType) {
return headerOption;
}
}
return null;
}
public boolean optionExists(CoapHeaderOptionType optionType) {
CoapHeaderOption option = getOption(optionType);
if (option == null){
return false;
} else return true;
}
public void addOption(CoapHeaderOption option) {
headerOptions.add(option);
/*TODO: only sort when options are serialized*/
Collections.sort(headerOptions);
}
public void addOption(CoapHeaderOptionType optionType, byte[] value){
addOption(new CoapHeaderOption(optionType, value));
}
public void removeOption(CoapHeaderOptionType optionType){
CoapHeaderOption headerOption;
// get elements of Vector
/* note: iterating over and changing a vector at the same time is not allowed */
int i = 0;
while (i < headerOptions.size()){
headerOption = headerOptions.get(i);
if (headerOption.getOptionType() == optionType) {
headerOptions.remove(i);
} else {
/* only increase when no element was removed*/
i++;
}
}
Collections.sort(headerOptions);
}
public void removeAll(){
headerOptions.clear();
}
public void copyFrom(CoapHeaderOptions origin){
for (CoapHeaderOption option : origin) {
addOption(option);
}
}
public int getOptionCount() {
return headerOptions.size();
}
public byte[] serialize() {
/* options are serialized here to be more efficient (only one byte array necessary)*/
int length = 0;
/* calculate the overall length first */
for (CoapHeaderOption option : headerOptions) {
length += option.getSerializeLength();
}
byte[] data = new byte[length];
int arrayIndex = 0;
int lastOptionNumber = 0; /* let's keep track of this */
for (CoapHeaderOption headerOption : headerOptions) {
/* TODO: move the serialization implementation to CoapHeaderOption */
int optionDelta = headerOption.getOptionTypeValue() - lastOptionNumber;
lastOptionNumber = headerOption.getOptionTypeValue();
// set length(s)
data[arrayIndex++] = (byte) (((optionDelta & 0x0F) << 4) | (headerOption.getShortLength() & 0x0F));
if (headerOption.hasLongLength()) {
data[arrayIndex++] = (byte) (headerOption.getLongLength() & 0xFF);
}
// copy option value
byte[] value = headerOption.getOptionData();
for (int i = 0; i < value.length; i++) {
data[arrayIndex++] = value[i];
}
}
serializedLength = length;
return data;
}
public int getDeserializedLength(){
return deserializedLength;
}
public int getSerializedLength() {
return serializedLength;
}
@Override
public Iterator<CoapHeaderOption> iterator() {
return headerOptions.iterator();
}
@Override
public String toString() {
String result = "\tOptions:\n";
for (CoapHeaderOption option : headerOptions) {
result += "\t\t" + option.toString() + "\n";
}
return result;
}
}
}
| 11106027-gokul | ws4d-jcoap/src/org/ws4d/coap/messages/AbstractCoapMessage.java | Java | asf20 | 23,178 |