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
// // ParserTestMacAppDelegate.h // ParserTestMac // // Created by Robbie Hanson on 11/22/09. // Copyright 2009 Deusty Designs, LLC.. All rights reserved. // #import <Cocoa/Cocoa.h> @interface ParserTestMacAppDelegate : NSObject <NSApplicationDelegate> { NSWindow *window; } @property (assign) IBOutlet NSWindow *window; @end
04081337-xmpp
Xcode/Testing/ParserTestMac/ParserTestMacAppDelegate.h
Objective-C
bsd
338
// // main.m // ParserTestMac // // Created by Robbie Hanson on 11/22/09. // Copyright 2009 Deusty Designs, LLC.. All rights reserved. // #import <Cocoa/Cocoa.h> int main(int argc, char *argv[]) { return NSApplicationMain(argc, (const char **) argv); }
04081337-xmpp
Xcode/Testing/ParserTestMac/main.m
Objective-C
bsd
264
#import <Cocoa/Cocoa.h> @class XMPPIDTracker; @interface TestIDTrackerAppDelegate : NSObject <NSApplicationDelegate> { XMPPIDTracker *idTracker; NSString *fetch1; NSString *fetch2; NSString *fetch3; NSString *fetch4; NSString *fetch5; NSString *fetch6; NSString *fetch7; NSString *fetch8; NSWindow *window; } @property (assign) IBOutlet NSWindow *window; @end
04081337-xmpp
Xcode/Testing/TestIDTracker/TestIDTracker/TestIDTrackerAppDelegate.h
Objective-C
bsd
379
{\rtf0\ansi{\fonttbl\f0\fswiss Helvetica;} {\colortbl;\red255\green255\blue255;} \paperw9840\paperh8400 \pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural \f0\b\fs24 \cf0 Engineering: \b0 \ Some people\ \ \b Human Interface Design: \b0 \ Some other people\ \ \b Testing: \b0 \ Hopefully not nobody\ \ \b Documentation: \b0 \ Whoever\ \ \b With special thanks to: \b0 \ Mom\ }
04081337-xmpp
Xcode/Testing/TestIDTracker/TestIDTracker/en.lproj/Credits.rtf
Rich Text Format
bsd
436
// // main.m // TestIDTracker // // Created by Robbie Hanson on 8/1/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #import <Cocoa/Cocoa.h> int main(int argc, char *argv[]) { return NSApplicationMain(argc, (const char **)argv); }
04081337-xmpp
Xcode/Testing/TestIDTracker/TestIDTracker/main.m
Objective-C
bsd
254
#import "TestIDTrackerAppDelegate.h" #import "XMPPIDTracker.h" #import "DDLog.h" #import "DDTTYLogger.h" // Log levels: off, error, warn, info, verbose static const int ddLogLevel = LOG_LEVEL_VERBOSE; @interface ExtendedTrackingInfo : XMPPBasicTrackingInfo { NSDate *timeSent; } @property (nonatomic, readonly) NSDate *timeSent; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation TestIDTrackerAppDelegate @synthesize window; - (NSString *)generateUUID { NSString *result = nil; CFUUIDRef uuid = CFUUIDCreate(NULL); if (uuid) { result = NSMakeCollectable(CFUUIDCreateString(NULL, uuid)); CFRelease(uuid); } return [result autorelease]; } - (void)scheduleFakeFetchResponseWithID:(NSString *)elementID obj:(id)obj timeout:(NSTimeInterval)timeout { NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:elementID, @"elementID", obj, @"obj", nil]; [NSTimer scheduledTimerWithTimeInterval:timeout target:self selector:@selector(fakeFetchResponse:) userInfo:dict repeats:NO]; } - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { [DDLog addLogger:[DDTTYLogger sharedInstance]]; idTracker = [[XMPPIDTracker alloc] initWithDispatchQueue:dispatch_get_main_queue()]; fetch1 = [[self generateUUID] retain]; fetch2 = [[self generateUUID] retain]; fetch3 = [[self generateUUID] retain]; fetch4 = [[self generateUUID] retain]; [idTracker addID:fetch1 target:self selector:@selector(simpleProcessFetch:withInfo:) timeout:2.0]; [idTracker addID:fetch2 target:self selector:@selector(simpleProcessFetch:withInfo:) timeout:4.0]; [self scheduleFakeFetchResponseWithID:fetch2 obj:@"quack" timeout:3.0]; void (^simpleBlock)(id, id <XMPPTrackingInfo>) = ^(id obj, id <XMPPTrackingInfo> info) { DDLogVerbose(@"simpleBlock(%@, %@)", obj, info); if (obj == nil) DDLogVerbose(@"timeout = %f", info.timeout); }; [idTracker addID:fetch3 block:simpleBlock timeout:6.0]; [idTracker addID:fetch4 block:simpleBlock timeout:8.0]; [self scheduleFakeFetchResponseWithID:fetch4 obj:@"moo" timeout:7.0]; fetch5 = [[self generateUUID] retain]; fetch6 = [[self generateUUID] retain]; fetch7 = [[self generateUUID] retain]; fetch8 = [[self generateUUID] retain]; SEL selector = @selector(advancedProcessFetch:withInfo:); ExtendedTrackingInfo *info5 = [[ExtendedTrackingInfo alloc] initWithTarget:self selector:selector timeout:10.0]; ExtendedTrackingInfo *info6 = [[ExtendedTrackingInfo alloc] initWithTarget:self selector:selector timeout:12.0]; [idTracker addID:fetch5 trackingInfo:info5]; [idTracker addID:fetch6 trackingInfo:info6]; [self scheduleFakeFetchResponseWithID:fetch6 obj:@"quack" timeout:11.0]; void (^advancedBlock)(NSString *, ExtendedTrackingInfo *) = ^(NSString *obj, ExtendedTrackingInfo *info) { DDLogVerbose(@"advancedBlock(%@, %@)", obj, info); if (obj == nil) DDLogVerbose(@"timeout = %f", info.timeout); else DDLogVerbose(@"timeSent = %@", info.timeSent); }; ExtendedTrackingInfo *info7 = [[ExtendedTrackingInfo alloc] initWithBlock:advancedBlock timeout:14.0]; ExtendedTrackingInfo *info8 = [[ExtendedTrackingInfo alloc] initWithBlock:advancedBlock timeout:16.0]; [idTracker addID:fetch7 trackingInfo:info7]; [idTracker addID:fetch8 trackingInfo:info8]; [self scheduleFakeFetchResponseWithID:fetch8 obj:@"moo" timeout:15.0]; } - (void)simpleProcessFetch:(id)obj withInfo:(id <XMPPTrackingInfo>)info { DDLogVerbose(@"simpleProcessFetch:%@ withInfo:%@", obj, info); if (obj == nil) DDLogVerbose(@"timeout = %f", info.timeout); } - (void)advancedProcessFetch:(id)obj withInfo:(ExtendedTrackingInfo *)info { DDLogVerbose(@"advancedProcessFetch:%@ withInfo:%@", obj, info); if (obj == nil) DDLogVerbose(@"timeout = %f", info.timeout); else DDLogVerbose(@"timeSent = %@", info.timeSent); } - (void)fakeFetchResponse:(NSTimer *)aTimer { DDLogVerbose(@"fakeFetchResponse:"); NSDictionary *dict = [aTimer userInfo]; NSString *elementID = [dict objectForKey:@"elementID"]; id obj = [dict objectForKey:@"obj"]; if ([idTracker invokeForID:elementID withObject:obj]) DDLogVerbose(@"got it"); else DDLogVerbose(@"huh?"); } @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation ExtendedTrackingInfo @synthesize timeSent; - (id)initWithTarget:(id)aTarget selector:(SEL)aSelector timeout:(NSTimeInterval)aTimeout { if ((self = [super initWithTarget:aTarget selector:aSelector timeout:aTimeout])) { timeSent = [[NSDate alloc] init]; } return self; } - (id)initWithBlock:(void (^)(id obj, id <XMPPTrackingInfo> info))aBlock timeout:(NSTimeInterval)aTimeout { if ((self = [super initWithBlock:aBlock timeout:aTimeout])) { timeSent = [[NSDate alloc] init]; } return self; } @end
04081337-xmpp
Xcode/Testing/TestIDTracker/TestIDTracker/TestIDTrackerAppDelegate.m
Objective-C
bsd
5,323
// // main.m // ParserTestPhone // // Created by Robbie Hanson on 11/22/09. // Copyright Deusty Designs, LLC. 2009. All rights reserved. // #import <UIKit/UIKit.h> int main(int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int retVal = UIApplicationMain(argc, argv, nil, nil); [pool release]; return retVal; }
04081337-xmpp
Xcode/Testing/ParserTestPhone/main.m
Objective-C
bsd
374
#import <UIKit/UIKit.h> @interface ParserTestPhoneAppDelegate : NSObject <UIApplicationDelegate> { UIWindow *window; } @property (nonatomic, retain) IBOutlet UIWindow *window; @end
04081337-xmpp
Xcode/Testing/ParserTestPhone/Classes/ParserTestPhoneAppDelegate.h
Objective-C
bsd
186
#import "ParserTestPhoneAppDelegate.h" #import "XMPPParser.h" #import "DDXML.h" #define PRINT_ELEMENTS NO @interface ParserTestPhoneAppDelegate (PrivateAPI) - (void)nonParserTest; - (void)parserTest; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation ParserTestPhoneAppDelegate @synthesize window; - (NSString *)stringToParse:(BOOL)full { NSMutableString *mStr = [NSMutableString stringWithCapacity:500]; if(full) { [mStr appendString:@"<stream:stream from='gmail.com' id='CA0CB0D98FE6FA62' version='1.0' " "xmlns:stream='http://etherx.jabber.org/streams' xmlns='jabber:client'>"]; } [mStr appendString:@" <stream:features>"]; [mStr appendString:@" <starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'>"]; [mStr appendString:@" <required/>"]; [mStr appendString:@" </starttls>"]; [mStr appendString:@" <mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>"]; [mStr appendString:@" <mechanism>X-GOOGLE-TOKEN</mechanism>"]; [mStr appendString:@" </mechanisms>"]; [mStr appendString:@" </stream:features>"]; [mStr appendString:@" <proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>"]; [mStr appendString:@" <success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>"]; [mStr appendString:@" <iq type='result'>"]; [mStr appendString:@" <bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'>"]; [mStr appendString:@" <jid>robbiehanson15@gmail.com/iPhoneTestBD221ED7</jid>"]; [mStr appendString:@" </bind>"]; [mStr appendString:@" </iq>"]; [mStr appendString:@" <team:deusty team:lead='robbie_hanson' xmlns:team='software'/>"]; [mStr appendString:@" <type><![CDATA[post]]></type>"]; [mStr appendString:@"<menu>"]; [mStr appendString:@" <food>"]; [mStr appendString:@" <pizza />"]; [mStr appendString:@" <spaghetti />"]; [mStr appendString:@" <turkey />"]; [mStr appendString:@" <pie />"]; [mStr appendString:@" <potatoes />"]; [mStr appendString:@" <gravy />"]; [mStr appendString:@" </food>"]; [mStr appendString:@" <drinks>"]; [mStr appendString:@" <sprite />"]; [mStr appendString:@" <drPepper />"]; [mStr appendString:@" <pepsi />"]; [mStr appendString:@" <coke />"]; [mStr appendString:@" <mtdew />"]; [mStr appendString:@" <beer />"]; [mStr appendString:@" <wine />"]; [mStr appendString:@" </drinks>"]; [mStr appendString:@"</menu>"]; if(full) { [mStr appendString:@"</stream:stream>"]; } return mStr; } - (NSData *)dataToParse:(BOOL)full { return [[self stringToParse:full] dataUsingEncoding:NSUTF8StringEncoding]; } - (void)applicationDidFinishLaunching:(UIApplication *)application { [self nonParserTest]; [self parserTest]; // Override point for customization after application launch [window makeKeyAndVisible]; } - (void)dealloc { [window release]; [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Non Parser //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSData *)nextTryFromData:(NSData *)data atOffset:(NSUInteger *)offset { NSData *term = [@">" dataUsingEncoding:NSUTF8StringEncoding]; NSUInteger termLength = [term length]; NSUInteger index = *offset; while((index + termLength) <= [data length]) { const void *dataBytes = (const void *)((void *)[data bytes] + index); if(memcmp(dataBytes, [term bytes], termLength) == 0) { NSUInteger length = (index - *offset) + termLength; NSRange range = NSMakeRange(*offset, length); *offset += length; return [data subdataWithRange:range]; } else { index++; } } *offset = index; return nil; } - (void)nonParserTest { NSData *dataToParse = [self dataToParse:NO]; NSDate *start = [NSDate date]; NSMutableData *mData = [NSMutableData data]; NSUInteger offset = 0; NSData *subdata = [self nextTryFromData:dataToParse atOffset:&offset]; while(subdata) { // NSString *str = [[NSString alloc] initWithData:subdata encoding:NSUTF8StringEncoding]; // NSLog(@"str: %@", str); // [str release]; [mData appendData:subdata]; DDXMLDocument *doc = [[DDXMLDocument alloc] initWithData:mData options:0 error:nil]; if(doc) { if(PRINT_ELEMENTS) { NSLog(@"\n\n%@\n", [doc XMLStringWithOptions:(NSXMLNodeCompactEmptyElement | NSXMLNodePrettyPrint)]); } [doc release]; [mData setLength:0]; } subdata = [self nextTryFromData:dataToParse atOffset:&offset]; } NSTimeInterval ellapsed = [start timeIntervalSinceNow] * -1.0; NSLog(@"NonParser test = %f seconds", ellapsed); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Parser //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)parserTest { NSData *dataToParse = [self dataToParse:YES]; NSDate *start = [NSDate date]; XMPPParser *parser = [[XMPPParser alloc] initWithDelegate:self]; [parser parseData:dataToParse]; NSTimeInterval ellapsed = [start timeIntervalSinceNow] * -1.0; NSLog(@"Parser test = %f seconds", ellapsed); } - (void)xmppParser:(XMPPParser *)sender didReadRoot:(NSXMLElement *)root { if(PRINT_ELEMENTS) { NSLog(@"xmppParser:didReadRoot: \n\n%@", [root XMLStringWithOptions:(NSXMLNodeCompactEmptyElement | NSXMLNodePrettyPrint)]); } } - (void)xmppParser:(XMPPParser *)sender didReadElement:(NSXMLElement *)element { if(PRINT_ELEMENTS) { NSLog(@"xmppParser:didReadElement: \n\n%@", [element XMLStringWithOptions:(NSXMLNodeCompactEmptyElement | NSXMLNodePrettyPrint)]); } } - (void)xmppParserDidEnd:(XMPPParser *)sender { if(PRINT_ELEMENTS) { NSLog(@"xmppParserDidEnd"); } } - (void)xmppParser:(XMPPParser *)sender didFail:(NSError *)error { if(PRINT_ELEMENTS) { NSLog(@"xmppParser:didFail: %@", error); } } @end
04081337-xmpp
Xcode/Testing/ParserTestPhone/Classes/ParserTestPhoneAppDelegate.m
Objective-C
bsd
6,206
// // TestElementReceiptAppDelegate.h // TestElementReceipt // // Created by Robbie Hanson on 8/5/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #import <Cocoa/Cocoa.h> @interface TestElementReceiptAppDelegate : NSObject <NSApplicationDelegate> { NSWindow *window; } @property (assign) IBOutlet NSWindow *window; @end
04081337-xmpp
Xcode/Testing/TestElementReceipt/TestElementReceipt/TestElementReceiptAppDelegate.h
Objective-C
bsd
345
{\rtf0\ansi{\fonttbl\f0\fswiss Helvetica;} {\colortbl;\red255\green255\blue255;} \paperw9840\paperh8400 \pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural \f0\b\fs24 \cf0 Engineering: \b0 \ Some people\ \ \b Human Interface Design: \b0 \ Some other people\ \ \b Testing: \b0 \ Hopefully not nobody\ \ \b Documentation: \b0 \ Whoever\ \ \b With special thanks to: \b0 \ Mom\ }
04081337-xmpp
Xcode/Testing/TestElementReceipt/TestElementReceipt/en.lproj/Credits.rtf
Rich Text Format
bsd
436
#import "TestElementReceiptAppDelegate.h" #import "XMPPStream.h" @interface XMPPElementReceipt (PrivateAPI) // Stolen from XMPPStream.m - (void)signalSuccess; - (void)signalFailure; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation TestElementReceiptAppDelegate @synthesize window; - (void)test1 { NSLog(@"========== test1 =========="); XMPPElementReceipt *receipt = [[[XMPPElementReceipt alloc] init] autorelease]; BOOL result = [receipt wait:0.0]; NSLog(@"NO =?= %@", (result ? @"YES" : @"NO")); } - (void)test2 { NSLog(@"========== test2 =========="); XMPPElementReceipt *receipt = [[[XMPPElementReceipt alloc] init] autorelease]; dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); double delayInSeconds = 2.0; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); dispatch_after(popTime, concurrentQueue, ^{ [receipt signalSuccess]; }); BOOL result = [receipt wait:4.0]; NSLog(@"YES =?= %@", (result ? @"YES" : @"NO")); } - (void)test3 { NSLog(@"========== test3 =========="); XMPPElementReceipt *receipt = [[[XMPPElementReceipt alloc] init] autorelease]; dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); double delayInSeconds = 5.0; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); dispatch_after(popTime, concurrentQueue, ^{ [receipt signalSuccess]; }); BOOL result1 = [receipt wait:3.0]; NSLog(@"NO =?= %@", (result1 ? @"YES" : @"NO")); BOOL result2 = [receipt wait:3.0]; NSLog(@"YES =?= %@", (result2 ? @"YES" : @"NO")); } - (void)test4 { NSLog(@"========== test4 =========="); XMPPElementReceipt *receipt = [[[XMPPElementReceipt alloc] init] autorelease]; dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); double delayInSeconds = 2.0; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); dispatch_after(popTime, concurrentQueue, ^{ [receipt signalFailure]; }); BOOL result1 = [receipt wait:4.0]; NSLog(@"NO =?= %@", (result1 ? @"YES" : @"NO")); BOOL result2 = [receipt wait:4.0]; NSLog(@"NO =?= %@", (result2 ? @"YES" : @"NO")); } - (void)test5 { NSLog(@"========== test5 =========="); XMPPElementReceipt *receipt = [[[XMPPElementReceipt alloc] init] autorelease]; dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); double delayInSeconds = 1.0; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); dispatch_after(popTime, concurrentQueue, ^{ [receipt signalSuccess]; }); BOOL result; do { result = [receipt wait:0.1]; NSLog(@"result == %@", (result ? @"YES" : @"NO")); } while (!result); } - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { dispatch_queue_t myQueue = dispatch_queue_create("Testing", NULL); dispatch_async(myQueue, ^{ [self test1]; [self test2]; [self test3]; [self test4]; [self test5]; }); } @end
04081337-xmpp
Xcode/Testing/TestElementReceipt/TestElementReceipt/TestElementReceiptAppDelegate.m
Objective-C
bsd
3,347
// // main.m // TestElementReceipt // // Created by Robbie Hanson on 8/5/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #import <Cocoa/Cocoa.h> int main(int argc, char *argv[]) { return NSApplicationMain(argc, (const char **)argv); }
04081337-xmpp
Xcode/Testing/TestElementReceipt/TestElementReceipt/main.m
Objective-C
bsd
259
#import "XMPPStream.h" #import "XMPPInternal.h" #import "XMPPParser.h" #import "XMPPJID.h" #import "XMPPIQ.h" #import "XMPPMessage.h" #import "XMPPPresence.h" #import "XMPPModule.h" #import "XMPPLogging.h" #import "NSData+XMPP.h" #import "NSXMLElement+XMPP.h" #import "XMPPSRVResolver.h" #import "DDList.h" #import <libkern/OSAtomic.h> #if TARGET_OS_IPHONE // Note: You may need to add the CFNetwork Framework to your project #import <CFNetwork/CFNetwork.h> #endif #if TARGET_OS_IPHONE #define SOCKET_BUFFER_SIZE 512 // bytes #else #define SOCKET_BUFFER_SIZE 1024 // bytes #endif /** * Seeing a return statements within an inner block * can sometimes be mistaken for a return point of the enclosing method. * This makes inline blocks a bit easier to read. **/ #define return_from_block return // Log levels: off, error, warn, info, verbose #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_INFO | XMPP_LOG_FLAG_SEND_RECV; // | XMPP_LOG_FLAG_TRACE; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #endif NSString *const XMPPStreamErrorDomain = @"XMPPStreamErrorDomain"; NSString *const XMPPStreamDidChangeMyJIDNotification = @"XMPPStreamDidChangeMyJID"; enum XMPPStreamFlags { kP2PInitiator = 1 << 0, // If set, we are the P2P initializer kIsSecure = 1 << 1, // If set, connection has been secured via SSL/TLS kIsAuthenticated = 1 << 2, // If set, authentication has succeeded kDidStartNegotiation = 1 << 3, // If set, negotiation has started at least once }; enum XMPPStreamConfig { kP2PMode = 1 << 0, // If set, the XMPPStream was initialized in P2P mode kResetByteCountPerConnection = 1 << 1, // If set, byte count should be reset per connection #if TARGET_OS_IPHONE kEnableBackgroundingOnSocket = 1 << 2, // If set, the VoIP flag should be set on the socket #endif }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @interface XMPPDigestAuthentication : NSObject { NSString *rspauth; NSString *realm; NSString *nonce; NSString *qop; NSString *username; NSString *password; NSString *cnonce; NSString *nc; NSString *digestURI; } - (id)initWithChallenge:(NSXMLElement *)challenge; - (NSString *)rspauth; - (NSString *)realm; - (void)setRealm:(NSString *)realm; - (void)setDigestURI:(NSString *)digestURI; - (void)setUsername:(NSString *)username password:(NSString *)password; - (NSString *)response; - (NSString *)base64EncodedFullResponse; @end @interface XMPPStream (PrivateAPI) - (void)cleanup; - (void)setIsSecure:(BOOL)flag; - (void)setIsAuthenticated:(BOOL)flag; - (void)continueSendElement:(NSXMLElement *)element withTag:(long)tag; - (void)startNegotiation; - (void)sendOpeningNegotiation; - (void)continueStartTLS:(NSMutableDictionary *)settings; - (void)setupKeepAliveTimer; - (void)keepAlive; @end @interface XMPPElementReceipt (PrivateAPI) - (void)signalSuccess; - (void)signalFailure; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation XMPPStream @synthesize tag = userTag; /** * Shared initialization between the various init methods. **/ - (void)commonInit { xmppQueue = dispatch_queue_create("xmppStreamQueue", NULL); parserQueue = dispatch_queue_create("xmppParserQueue", NULL); multicastDelegate = [[GCDMulticastDelegate alloc] init]; state = STATE_XMPP_DISCONNECTED; flags = 0; config = 0; numberOfBytesSent = 0; numberOfBytesReceived = 0; parser = [(XMPPParser *)[XMPPParser alloc] initWithDelegate:self]; hostPort = 5222; keepAliveInterval = DEFAULT_KEEPALIVE_INTERVAL; registeredModules = [[DDList alloc] init]; autoDelegateDict = [[NSMutableDictionary alloc] init]; receipts = [[NSMutableArray alloc] init]; // Setup and start the utility thread. // We need to be careful to ensure the thread doesn't retain a reference to us longer than necessary. xmppUtilityThread = [[NSThread alloc] initWithTarget:[self class] selector:@selector(xmppThreadMain) object:nil]; [[xmppUtilityThread threadDictionary] setObject:self forKey:@"XMPPStream"]; [xmppUtilityThread start]; } /** * Standard XMPP initialization. * The stream is a standard client to server connection. **/ - (id)init { if ((self = [super init])) { // Common initialization [self commonInit]; // Initialize socket asyncSocket = [(GCDAsyncSocket *)[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:xmppQueue]; } return self; } /** * Peer to Peer XMPP initialization. * The stream is a direct client to client connection as outlined in XEP-0174. **/ - (id)initP2PFrom:(XMPPJID *)jid { if ((self = [super init])) { // Common initialization [self commonInit]; // Store JID myJID = [jid retain]; // We do not initialize the socket, since the connectP2PWithSocket: method might be used. // Initialize configuration config = kP2PMode; } return self; } /** * Standard deallocation method. * Every object variable declared in the header file should be released here. **/ - (void)dealloc { dispatch_release(xmppQueue); dispatch_release(parserQueue); [multicastDelegate release]; [asyncSocket setDelegate:nil delegateQueue:NULL]; [asyncSocket disconnect]; [asyncSocket release]; [socketBuffer release]; [parser setDelegate:nil]; [parser release]; [parserError release]; [hostName release]; [tempPassword release]; [myJID release]; [remoteJID release]; [myPresence release]; [rootElement release]; if (keepAliveTimer) { dispatch_source_cancel(keepAliveTimer); } [registeredModules release]; [autoDelegateDict release]; [srvResolver release]; [srvResults release]; for (XMPPElementReceipt *receipt in receipts) { [receipt signalFailure]; } [receipts release]; [[self class] performSelector:@selector(xmppThreadStop) onThread:xmppUtilityThread withObject:nil waitUntilDone:NO]; [userTag release]; [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Properties //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSString *)hostName { if (dispatch_get_current_queue() == xmppQueue) { return hostName; } else { __block NSString *result; dispatch_sync(xmppQueue, ^{ result = [hostName retain]; }); return [result autorelease]; } } - (void)setHostName:(NSString *)newHostName { if (dispatch_get_current_queue() == xmppQueue) { if (hostName != newHostName) { [hostName release]; hostName = [newHostName copy]; } } else { NSString *newHostNameCopy = [newHostName copy]; dispatch_async(xmppQueue, ^{ [hostName release]; hostName = [newHostNameCopy retain]; }); [newHostNameCopy release]; } } - (UInt16)hostPort { if (dispatch_get_current_queue() == xmppQueue) { return hostPort; } else { __block UInt16 result; dispatch_sync(xmppQueue, ^{ result = hostPort; }); return result; } } - (void)setHostPort:(UInt16)newHostPort { dispatch_block_t block = ^{ hostPort = newHostPort; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_async(xmppQueue, block); } - (XMPPJID *)myJID { if (dispatch_get_current_queue() == xmppQueue) { return myJID; } else { __block XMPPJID *result; dispatch_sync(xmppQueue, ^{ result = [myJID retain]; }); return [result autorelease]; } } - (void)setMyJID:(XMPPJID *)newMyJID { // XMPPJID is an immutable class (copy == retain) dispatch_block_t block = ^{ if (myJID != newMyJID) { [myJID release]; myJID = [newMyJID retain]; } [[NSNotificationCenter defaultCenter] postNotificationName:XMPPStreamDidChangeMyJIDNotification object:self]; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_async(xmppQueue, block); } - (XMPPJID *)remoteJID { if (dispatch_get_current_queue() == xmppQueue) { return remoteJID; } else { __block XMPPJID *result; dispatch_sync(xmppQueue, ^{ result = [remoteJID retain]; }); return [result autorelease]; } } - (XMPPPresence *)myPresence { if (dispatch_get_current_queue() == xmppQueue) { return myPresence; } else { __block XMPPPresence *result; dispatch_sync(xmppQueue, ^{ result = [myPresence retain]; }); return [result autorelease]; } } - (NSTimeInterval)keepAliveInterval { if (dispatch_get_current_queue() == xmppQueue) { return keepAliveInterval; } else { __block NSTimeInterval result; dispatch_sync(xmppQueue, ^{ result = keepAliveInterval; }); return result; } } - (void)setKeepAliveInterval:(NSTimeInterval)interval { dispatch_block_t block = ^{ if (keepAliveInterval != interval) { if (interval <= 0.0) keepAliveInterval = interval; else keepAliveInterval = MAX(interval, MIN_KEEPALIVE_INTERVAL); [self setupKeepAliveTimer]; } }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_async(xmppQueue, block); } - (UInt64)numberOfBytesSent { if (dispatch_get_current_queue() == xmppQueue) { return numberOfBytesSent; } else { __block UInt64 result; dispatch_sync(xmppQueue, ^{ result = numberOfBytesSent; }); return result; } } - (UInt64)numberOfBytesReceived { if (dispatch_get_current_queue() == xmppQueue) { return numberOfBytesReceived; } else { __block UInt64 result; dispatch_sync(xmppQueue, ^{ result = numberOfBytesReceived; }); return result; } } - (BOOL)resetByteCountPerConnection { __block BOOL result; dispatch_block_t block = ^{ result = (config & kResetByteCountPerConnection) ? YES : NO; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); return result; } - (void)setResetByteCountPerConnection:(BOOL)flag { dispatch_block_t block = ^{ if (flag) config |= kResetByteCountPerConnection; else config &= ~kResetByteCountPerConnection; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_async(xmppQueue, block); } #if TARGET_OS_IPHONE - (BOOL)enableBackgroundingOnSocket { __block BOOL result; dispatch_block_t block = ^{ result = (config & kEnableBackgroundingOnSocket) ? YES : NO; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); return result; } - (void)setEnableBackgroundingOnSocket:(BOOL)flag { dispatch_block_t block = ^{ if (flag) config |= kEnableBackgroundingOnSocket; else config &= ~kEnableBackgroundingOnSocket; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_async(xmppQueue, block); } #endif //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Configuration //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)addDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue { // Asynchronous operation (if outside xmppQueue) dispatch_block_t block = ^{ [multicastDelegate addDelegate:delegate delegateQueue:delegateQueue]; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_async(xmppQueue, block); } - (void)removeDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue { // Synchronous operation dispatch_block_t block = ^{ [multicastDelegate removeDelegate:delegate delegateQueue:delegateQueue]; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); } - (void)removeDelegate:(id)delegate { // Synchronous operation dispatch_block_t block = ^{ [multicastDelegate removeDelegate:delegate]; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); } /** * Returns YES if the stream was opened in P2P mode. * In other words, the stream was created via initP2PFrom: to use XEP-0174. **/ - (BOOL)isP2P { if (dispatch_get_current_queue() == xmppQueue) { return (config & kP2PMode) ? YES : NO; } else { __block BOOL result; dispatch_sync(xmppQueue, ^{ result = (config & kP2PMode) ? YES : NO; }); return result; } } - (BOOL)isP2PInitiator { if (dispatch_get_current_queue() == xmppQueue) { return ((config & kP2PMode) && (flags & kP2PInitiator)); } else { __block BOOL result; dispatch_sync(xmppQueue, ^{ result = ((config & kP2PMode) && (flags & kP2PInitiator)); }); return result; } } - (BOOL)isP2PRecipient { if (dispatch_get_current_queue() == xmppQueue) { return ((config & kP2PMode) && !(flags & kP2PInitiator)); } else { __block BOOL result; dispatch_sync(xmppQueue, ^{ result = ((config & kP2PMode) && !(flags & kP2PInitiator)); }); return result; } } - (BOOL)didStartNegotiation { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); return (flags & kDidStartNegotiation) ? YES : NO; } - (void)setDidStartNegotiation:(BOOL)flag { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); if (flag) flags |= kDidStartNegotiation; else flags &= ~kDidStartNegotiation; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Connection State //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Returns YES if the connection is closed, and thus no stream is open. * If the stream is neither disconnected, nor connected, then a connection is currently being established. **/ - (BOOL)isDisconnected { __block BOOL result; dispatch_block_t block = ^{ result = (state == STATE_XMPP_DISCONNECTED); }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); return result; } /** * Returns YES if the connection is open, and the stream has been properly established. * If the stream is neither disconnected, nor connected, then a connection is currently being established. **/ - (BOOL)isConnected { __block BOOL result; dispatch_block_t block = ^{ result = (state == STATE_XMPP_CONNECTED); }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); return result; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark C2S Connection //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (BOOL)connectToHost:(NSString *)host onPort:(UInt16)port error:(NSError **)errPtr { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); BOOL result = [asyncSocket connectToHost:host onPort:port error:errPtr]; if (result && [self resetByteCountPerConnection]) { numberOfBytesSent = 0; numberOfBytesReceived = 0; } return result; } - (BOOL)connect:(NSError **)errPtr { XMPPLogTrace(); __block BOOL result = NO; __block NSError *err = nil; dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if (state != STATE_XMPP_DISCONNECTED) { NSString *errMsg = @"Attempting to connect while already connected or connecting."; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidState userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } if ([self isP2P]) { NSString *errMsg = @"P2P streams must use either connectTo:withAddress: or connectP2PWithSocket:."; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidType userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } if (myJID == nil) { // Note: If you wish to use anonymous authentication, you should still set myJID prior to calling connect. // You can simply set it to something like "anonymous@<domain>", where "<domain>" is the proper domain. // After the authentication process, you can query the myJID property to see what your assigned JID is. // // Setting myJID allows the framework to follow the xmpp protocol properly, // and it allows the framework to connect to servers without a DNS entry. // // For example, one may setup a private xmpp server for internal testing on their local network. // The xmpp domain of the server may be something like "testing.mycompany.com", // but since the server is internal, an IP (192.168.1.22) is used as the hostname to connect. // // Proper connection requires a TCP connection to the IP (192.168.1.22), // but the xmpp handshake requires the xmpp domain (testing.mycompany.com). NSString *errMsg = @"You must set myJID before calling connect."; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidProperty userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } // Notify delegates [multicastDelegate xmppStreamWillConnect:self]; if ([hostName length] == 0) { // Resolve the hostName via myJID SRV resolution state = STATE_XMPP_RESOLVING_SRV; [srvResolver release]; srvResolver = [[XMPPSRVResolver alloc] initWithdDelegate:self delegateQueue:xmppQueue resolverQueue:NULL]; [srvResults release]; srvResults = nil; srvResultsIndex = 0; NSString *srvName = [XMPPSRVResolver srvNameFromXMPPDomain:[myJID domain]]; [srvResolver startWithSRVName:srvName timeout:30.0]; result = YES; } else { // Open TCP connection to the configured hostName. state = STATE_XMPP_CONNECTING; result = [self connectToHost:hostName onPort:hostPort error:&err]; if (!result) { state = STATE_XMPP_DISCONNECTED; } } [err retain]; [pool drain]; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); if (errPtr) *errPtr = [err autorelease]; else [err release]; return result; } - (BOOL)oldSchoolSecureConnect:(NSError **)errPtr { XMPPLogTrace(); __block BOOL result; __block NSError *err = nil; dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Go through the regular connect routine result = [self connect:&err]; if (result) { // Mark the secure flag. // We will check the flag in socket:didConnectToHost:port: [self setIsSecure:YES]; } [err retain]; [pool drain]; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); if (errPtr) *errPtr = [err autorelease]; else [err release]; return result; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark P2P Connection //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Starts a P2P connection to the given user and given address. * This method only works with XMPPStream objects created using the initP2P method. * * The given address is specified as a sockaddr structure wrapped in a NSData object. * For example, a NSData object returned from NSNetservice's addresses method. **/ - (BOOL)connectTo:(XMPPJID *)jid withAddress:(NSData *)remoteAddr error:(NSError **)errPtr { XMPPLogTrace(); __block BOOL result = YES; __block NSError *err = nil; dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if (state != STATE_XMPP_DISCONNECTED) { NSString *errMsg = @"Attempting to connect while already connected or connecting."; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidState userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } if (![self isP2P]) { NSString *errMsg = @"Non P2P streams must use the connect: method"; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidType userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } // Turn on P2P initiator flag flags |= kP2PInitiator; // Store remoteJID [remoteJID release]; remoteJID = [jid copy]; NSAssert((asyncSocket == nil), @"Forgot to release the previous asyncSocket instance."); // Notify delegates [multicastDelegate xmppStreamWillConnect:self]; // Update state state = STATE_XMPP_CONNECTING; // Initailize socket asyncSocket = [(GCDAsyncSocket *)[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:xmppQueue]; result = [asyncSocket connectToAddress:remoteAddr error:&err]; if (result == NO) { state = STATE_XMPP_DISCONNECTED; } else if ([self resetByteCountPerConnection]) { numberOfBytesSent = 0; numberOfBytesReceived = 0; } [err retain]; [pool drain]; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); if (errPtr) *errPtr = [err autorelease]; else [err release]; return result; } /** * Starts a P2P connection with the given accepted socket. * This method only works with XMPPStream objects created using the initP2P method. * * The given socket should be a socket that has already been accepted. * The remoteJID will be extracted from the opening stream negotiation. **/ - (BOOL)connectP2PWithSocket:(GCDAsyncSocket *)acceptedSocket error:(NSError **)errPtr { XMPPLogTrace(); __block BOOL result = YES; __block NSError *err = nil; dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if (state != STATE_XMPP_DISCONNECTED) { NSString *errMsg = @"Attempting to connect while already connected or connecting."; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidState userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } if (![self isP2P]) { NSString *errMsg = @"Non P2P streams must use the connect: method"; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidType userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } if (acceptedSocket == nil) { NSString *errMsg = @"Parameter acceptedSocket is nil."; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidParameter userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } // Turn off P2P initiator flag flags &= ~kP2PInitiator; NSAssert((asyncSocket == nil), @"Forgot to release the previous asyncSocket instance."); // Store and configure socket asyncSocket = [acceptedSocket retain]; [asyncSocket setDelegate:self delegateQueue:xmppQueue]; // Notify delegates [multicastDelegate xmppStream:self socketDidConnect:asyncSocket]; // Update state state = STATE_XMPP_CONNECTING; if ([self resetByteCountPerConnection]) { numberOfBytesSent = 0; numberOfBytesReceived = 0; } // Start the XML stream [self startNegotiation]; [err retain]; [pool drain]; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); if (errPtr) *errPtr = [err autorelease]; else [err release]; return result; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Disconnect //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Closes the connection to the remote host. **/ - (void)disconnect { XMPPLogTrace(); dispatch_block_t block = ^{ if (state != STATE_XMPP_DISCONNECTED) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [multicastDelegate xmppStreamWasToldToDisconnect:self]; if (state == STATE_XMPP_RESOLVING_SRV) { [srvResolver stop]; [srvResolver release]; srvResolver = nil; state = STATE_XMPP_DISCONNECTED; [multicastDelegate xmppStreamDidDisconnect:self withError:nil]; } else { [asyncSocket disconnect]; // Everthing will be handled in socketDidDisconnect:withError: } [pool drain]; } }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); } - (void)disconnectAfterSending { XMPPLogTrace(); dispatch_block_t block = ^{ if (state != STATE_XMPP_DISCONNECTED) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [multicastDelegate xmppStreamWasToldToDisconnect:self]; if (state == STATE_XMPP_RESOLVING_SRV) { [srvResolver stop]; [srvResolver release]; srvResolver = nil; state = STATE_XMPP_DISCONNECTED; [multicastDelegate xmppStreamDidDisconnect:self withError:nil]; } else { [asyncSocket disconnectAfterWriting]; // Everthing will be handled in socketDidDisconnect:withError: } [pool drain]; } }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_async(xmppQueue, block); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Security //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Returns YES if SSL/TLS has been used to secure the connection. **/ - (BOOL)isSecure { if (dispatch_get_current_queue() == xmppQueue) { return (flags & kIsSecure) ? YES : NO; } else { __block BOOL result; dispatch_sync(xmppQueue, ^{ result = (flags & kIsSecure) ? YES : NO; }); return result; } } - (void)setIsSecure:(BOOL)flag { dispatch_block_t block = ^{ if(flag) flags |= kIsSecure; else flags &= ~kIsSecure; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_async(xmppQueue, block); } - (BOOL)supportsStartTLS { __block BOOL result = NO; dispatch_block_t block = ^{ // The root element can be properly queried for authentication mechanisms anytime after the //stream:features are received, and TLS has been setup (if required) if (state >= STATE_XMPP_POST_NEGOTIATION) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSXMLElement *features = [rootElement elementForName:@"stream:features"]; NSXMLElement *starttls = [features elementForName:@"starttls" xmlns:@"urn:ietf:params:xml:ns:xmpp-tls"]; result = (starttls != nil); [pool drain]; } }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); return result; } - (void)sendStartTLSRequest { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); NSString *starttls = @"<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>"; NSData *outgoingData = [starttls dataUsingEncoding:NSUTF8StringEncoding]; XMPPLogSend(@"SEND: %@", starttls); numberOfBytesSent += [outgoingData length]; [asyncSocket writeData:outgoingData withTimeout:TIMEOUT_XMPP_WRITE tag:TAG_XMPP_WRITE_STREAM]; } - (BOOL)secureConnection:(NSError **)errPtr { XMPPLogTrace(); __block BOOL result = YES; __block NSError *err = nil; dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if (state != STATE_XMPP_CONNECTED) { NSString *errMsg = @"Please wait until the stream is connected."; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidState userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } if (![self supportsStartTLS]) { NSString *errMsg = @"The server does not support startTLS."; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamUnsupportedAction userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } // Update state state = STATE_XMPP_STARTTLS_1; // Send the startTLS XML request [self sendStartTLSRequest]; // We do not mark the stream as secure yet. // We're waiting to receive the <proceed/> response from the // server before we actually start the TLS handshake. [pool drain]; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); return result; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Registration //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * This method checks the stream features of the connected server to determine if in-band registartion is supported. * If we are not connected to a server, this method simply returns NO. **/ - (BOOL)supportsInBandRegistration { __block BOOL result = NO; dispatch_block_t block = ^{ // The root element can be properly queried for authentication mechanisms anytime after the // stream:features are received, and TLS has been setup (if required) if (state >= STATE_XMPP_POST_NEGOTIATION) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSXMLElement *features = [rootElement elementForName:@"stream:features"]; NSXMLElement *reg = [features elementForName:@"register" xmlns:@"http://jabber.org/features/iq-register"]; result = (reg != nil); [pool drain]; } }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); return result; } /** * This method attempts to register a new user on the server using the given username and password. * The result of this action will be returned via the delegate methods. * * If the XMPPStream is not connected, or the server doesn't support in-band registration, this method does nothing. **/ - (BOOL)registerWithPassword:(NSString *)password error:(NSError **)errPtr { XMPPLogTrace(); __block BOOL result = YES; __block NSError *err = nil; dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if (state != STATE_XMPP_CONNECTED) { NSString *errMsg = @"Please wait until the stream is connected."; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidState userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } if (myJID == nil) { NSString *errMsg = @"You must set myJID before calling registerWithPassword:error:."; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidProperty userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } if (![self supportsInBandRegistration]) { NSString *errMsg = @"The server does not support in band registration."; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamUnsupportedAction userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } NSString *username = [myJID user]; NSXMLElement *queryElement = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:register"]; [queryElement addChild:[NSXMLElement elementWithName:@"username" stringValue:username]]; [queryElement addChild:[NSXMLElement elementWithName:@"password" stringValue:password]]; NSXMLElement *iqElement = [NSXMLElement elementWithName:@"iq"]; [iqElement addAttributeWithName:@"type" stringValue:@"set"]; [iqElement addChild:queryElement]; NSString *outgoingStr = [iqElement compactXMLString]; NSData *outgoingData = [outgoingStr dataUsingEncoding:NSUTF8StringEncoding]; XMPPLogSend(@"SEND: %@", outgoingStr); numberOfBytesSent += [outgoingData length]; [asyncSocket writeData:outgoingData withTimeout:TIMEOUT_XMPP_WRITE tag:TAG_XMPP_WRITE_STREAM]; // Update state state = STATE_XMPP_REGISTERING; [pool drain]; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); return result; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Authentication //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * This method checks the stream features of the connected server to determine if SASL Anonymous Authentication (XEP-0175) * is supported. If we are not connected to a server, this method simply returns NO. **/ - (BOOL)supportsAnonymousAuthentication { __block BOOL result = NO; dispatch_block_t block = ^{ // The root element can be properly queried for authentication mechanisms anytime after the // stream:features are received, and TLS has been setup (if required) if (state >= STATE_XMPP_POST_NEGOTIATION) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSXMLElement *features = [rootElement elementForName:@"stream:features"]; NSXMLElement *mech = [features elementForName:@"mechanisms" xmlns:@"urn:ietf:params:xml:ns:xmpp-sasl"]; NSArray *mechanisms = [mech elementsForName:@"mechanism"]; for (NSXMLElement *mechanism in mechanisms) { if ([[mechanism stringValue] isEqualToString:@"ANONYMOUS"]) { result = YES; break; } } [pool drain]; } }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); return result; } /** * This method checks the stream features of the connected server to determine if plain authentication is supported. * If we are not connected to a server, this method simply returns NO. **/ - (BOOL)supportsPlainAuthentication { __block BOOL result = NO; dispatch_block_t block = ^{ // The root element can be properly queried for authentication mechanisms anytime after the //stream:features are received, and TLS has been setup (if required) if (state >= STATE_XMPP_POST_NEGOTIATION) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSXMLElement *features = [rootElement elementForName:@"stream:features"]; NSXMLElement *mech = [features elementForName:@"mechanisms" xmlns:@"urn:ietf:params:xml:ns:xmpp-sasl"]; NSArray *mechanisms = [mech elementsForName:@"mechanism"]; for (NSXMLElement *mechanism in mechanisms) { if ([[mechanism stringValue] isEqualToString:@"PLAIN"]) { result = YES; break; } } [pool release]; } }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); return result; } /** * This method checks the stream features of the connected server to determine if digest authentication is supported. * If we are not connected to a server, this method simply returns NO. * * This is the preferred authentication technique, and will be used if the server supports it. **/ - (BOOL)supportsDigestMD5Authentication { __block BOOL result = NO; dispatch_block_t block = ^{ // The root element can be properly queried for authentication mechanisms anytime after the // stream:features are received, and TLS has been setup (if required) if (state >= STATE_XMPP_POST_NEGOTIATION) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSXMLElement *features = [rootElement elementForName:@"stream:features"]; NSXMLElement *mech = [features elementForName:@"mechanisms" xmlns:@"urn:ietf:params:xml:ns:xmpp-sasl"]; NSArray *mechanisms = [mech elementsForName:@"mechanism"]; for (NSXMLElement *mechanism in mechanisms) { if ([[mechanism stringValue] isEqualToString:@"DIGEST-MD5"]) { result = YES; break; } } [pool drain]; } }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); return result; } /** * This method only applies to servers that don't support XMPP version 1.0, as defined in RFC 3920. * With these servers, we attempt to discover supported authentication modes via the jabber:iq:auth namespace. **/ - (BOOL)supportsDeprecatedPlainAuthentication { __block BOOL result = NO; dispatch_block_t block = ^{ // The root element can be properly queried for authentication mechanisms anytime after the // stream:features are received, and TLS has been setup (if required) if (state >= STATE_XMPP_POST_NEGOTIATION) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Search for an iq element within the rootElement. // Recall that some servers might stupidly add a "jabber:client" namespace which might cause problems // if we simply used the elementForName method. NSXMLElement *iq = nil; NSUInteger i, count = [rootElement childCount]; for (i = 0; i < count; i++) { NSXMLNode *childNode = [rootElement childAtIndex:i]; if ([childNode kind] == NSXMLElementKind) { if ([[childNode name] isEqualToString:@"iq"]) { iq = (NSXMLElement *)childNode; } } } NSXMLElement *query = [iq elementForName:@"query" xmlns:@"jabber:iq:auth"]; NSXMLElement *plain = [query elementForName:@"password"]; result = (plain != nil); [pool drain]; } }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); return result; } /** * This method only applies to servers that don't support XMPP version 1.0, as defined in RFC 3920. * With these servers, we attempt to discover supported authentication modes via the jabber:iq:auth namespace. **/ - (BOOL)supportsDeprecatedDigestAuthentication { __block BOOL result = NO; dispatch_block_t block = ^{ // The root element can be properly queried for authentication mechanisms anytime after the // stream:features are received, and TLS has been setup (if required) if (state >= STATE_XMPP_POST_NEGOTIATION) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Search for an iq element within the rootElement. // Recall that some servers might stupidly add a "jabber:client" namespace which might cause problems // if we simply used the elementForName method. NSXMLElement *iq = nil; NSUInteger i, count = [rootElement childCount]; for (i = 0; i < count; i++) { NSXMLNode *childNode = [rootElement childAtIndex:i]; if ([childNode kind] == NSXMLElementKind) { if ([[childNode name] isEqualToString:@"iq"]) { iq = (NSXMLElement *)childNode; } } } NSXMLElement *query = [iq elementForName:@"query" xmlns:@"jabber:iq:auth"]; NSXMLElement *digest = [query elementForName:@"digest"]; result = (digest != nil); [pool drain]; } }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); return result; } /** * This method attempts to sign-in to the server using the configured myJID and given password. * If this method immediately fails **/ - (BOOL)authenticateWithPassword:(NSString *)password error:(NSError **)errPtr { XMPPLogTrace(); __block BOOL result = YES; __block NSError *err = nil; dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if (state != STATE_XMPP_CONNECTED) { NSString *errMsg = @"Please wait until the stream is connected."; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidState userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } if (myJID == nil) { NSString *errMsg = @"You must set myJID before calling authenticateWithPassword:error:."; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidProperty userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } if ([self supportsDigestMD5Authentication]) { NSString *auth = @"<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='DIGEST-MD5'/>"; NSData *outgoingData = [auth dataUsingEncoding:NSUTF8StringEncoding]; XMPPLogSend(@"SEND: %@", auth); numberOfBytesSent += [outgoingData length]; [asyncSocket writeData:outgoingData withTimeout:TIMEOUT_XMPP_WRITE tag:TAG_XMPP_WRITE_STREAM]; // Save authentication information [tempPassword release]; tempPassword = [password copy]; // Update state state = STATE_XMPP_AUTH_1; } else if ([self supportsPlainAuthentication]) { // From RFC 4616 - PLAIN SASL Mechanism: // [authzid] UTF8NUL authcid UTF8NUL passwd // // authzid: authorization identity // authcid: authentication identity (username) // passwd : password for authcid NSString *username = [myJID user]; NSString *payload = [NSString stringWithFormat:@"%C%@%C%@", 0, username, 0, password]; NSString *base64 = [[payload dataUsingEncoding:NSUTF8StringEncoding] base64Encoded]; NSXMLElement *auth = [NSXMLElement elementWithName:@"auth" xmlns:@"urn:ietf:params:xml:ns:xmpp-sasl"]; [auth addAttributeWithName:@"mechanism" stringValue:@"PLAIN"]; [auth setStringValue:base64]; NSString *outgoingStr = [auth compactXMLString]; NSData *outgoingData = [outgoingStr dataUsingEncoding:NSUTF8StringEncoding]; XMPPLogSend(@"SEND: %@", outgoingStr); numberOfBytesSent += [outgoingData length]; [asyncSocket writeData:outgoingData withTimeout:TIMEOUT_XMPP_WRITE tag:TAG_XMPP_WRITE_STREAM]; // Update state state = STATE_XMPP_AUTH_1; } else { // The server does not appear to support SASL authentication (at least any type we can use) // So we'll revert back to the old fashioned jabber:iq:auth mechanism NSString *username = [myJID user]; NSString *resource = [myJID resource]; if ([resource length] == 0) { // If resource is nil or empty, we need to auto-create one resource = [self generateUUID]; } NSXMLElement *queryElement = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:auth"]; [queryElement addChild:[NSXMLElement elementWithName:@"username" stringValue:username]]; [queryElement addChild:[NSXMLElement elementWithName:@"resource" stringValue:resource]]; if ([self supportsDeprecatedDigestAuthentication]) { NSString *rootID = [[[self rootElement] attributeForName:@"id"] stringValue]; NSString *digestStr = [NSString stringWithFormat:@"%@%@", rootID, password]; NSData *digestData = [digestStr dataUsingEncoding:NSUTF8StringEncoding]; NSString *digest = [[digestData sha1Digest] hexStringValue]; [queryElement addChild:[NSXMLElement elementWithName:@"digest" stringValue:digest]]; } else { [queryElement addChild:[NSXMLElement elementWithName:@"password" stringValue:password]]; } NSXMLElement *iqElement = [NSXMLElement elementWithName:@"iq"]; [iqElement addAttributeWithName:@"type" stringValue:@"set"]; [iqElement addChild:queryElement]; NSString *outgoingStr = [iqElement compactXMLString]; NSData *outgoingData = [outgoingStr dataUsingEncoding:NSUTF8StringEncoding]; XMPPLogSend(@"SEND: %@", outgoingStr); numberOfBytesSent += [outgoingData length]; [asyncSocket writeData:outgoingData withTimeout:TIMEOUT_XMPP_WRITE tag:TAG_XMPP_WRITE_STREAM]; // Update state state = STATE_XMPP_AUTH_1; } [err retain]; [pool drain]; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); if (errPtr) *errPtr = [err autorelease]; else [err release]; return result; } /** * This method attempts to sign-in to the using SASL Anonymous Authentication (XEP-0175) **/ - (BOOL)authenticateAnonymously:(NSError **)errPtr { XMPPLogTrace(); __block BOOL result = YES; __block NSError *err = nil; dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if (state != STATE_XMPP_CONNECTED) { NSString *errMsg = @"Please wait until the stream is connected."; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidState userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } if (![self supportsAnonymousAuthentication]) { NSString *errMsg = @"The server does not support anonymous authentication."; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamUnsupportedAction userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } NSXMLElement *auth = [NSXMLElement elementWithName:@"auth" xmlns:@"urn:ietf:params:xml:ns:xmpp-sasl"]; [auth addAttributeWithName:@"mechanism" stringValue:@"ANONYMOUS"]; NSString *outgoingStr = [auth compactXMLString]; NSData *outgoingData = [outgoingStr dataUsingEncoding:NSUTF8StringEncoding]; XMPPLogSend(@"SEND: %@", outgoingStr); numberOfBytesSent += [outgoingData length]; [asyncSocket writeData:outgoingData withTimeout:TIMEOUT_XMPP_WRITE tag:TAG_XMPP_WRITE_STREAM]; // Update state state = STATE_XMPP_AUTH_3; [err retain]; [pool drain]; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); if (errPtr) *errPtr = [err autorelease]; else [err release]; return result; } - (BOOL)isAuthenticated { if (dispatch_get_current_queue() == xmppQueue) { return (flags & kIsAuthenticated) ? YES : NO; } else { __block BOOL result; dispatch_sync(xmppQueue, ^{ result = (flags & kIsAuthenticated) ? YES : NO; }); return result; } } - (void)setIsAuthenticated:(BOOL)flag { dispatch_block_t block = ^{ if(flag) flags |= kIsAuthenticated; else flags &= ~kIsAuthenticated; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_async(xmppQueue, block); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark General Methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * This method will return the root element of the document. * This element contains the opening <stream:stream/> and <stream:features/> tags received from the server * when the XML stream was opened. * * Note: The rootElement is empty, and does not contain all the XML elements the stream has received during it's * connection. This is done for performance reasons and for the obvious benefit of being more memory efficient. **/ - (NSXMLElement *)rootElement { if (dispatch_get_current_queue() == xmppQueue) { return rootElement; } else { __block NSXMLElement *result = nil; dispatch_sync(xmppQueue, ^{ result = [rootElement copy]; }); return [result autorelease]; } } /** * Returns the version attribute from the servers's <stream:stream/> element. * This should be at least 1.0 to be RFC 3920 compliant. * If no version number was set, the server is not RFC compliant, and 0 is returned. **/ - (float)serverXmppStreamVersionNumber { if (dispatch_get_current_queue() == xmppQueue) { return [rootElement attributeFloatValueForName:@"version" withDefaultValue:0.0F]; } else { __block float result; dispatch_sync(xmppQueue, ^{ result = [rootElement attributeFloatValueForName:@"version" withDefaultValue:0.0F]; }); return result; } } - (void)sendIQ:(XMPPIQ *)iq withTag:(long)tag { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); NSAssert(state == STATE_XMPP_CONNECTED, @"Invoked with incorrect state"); // We're getting ready to send an IQ. // We need to notify delegates of this action to allow them to optionally alter the IQ element. SEL selector = @selector(xmppStream:willSendIQ:); if ([multicastDelegate countForSelector:selector] == 0) { // None of the delegates implement the method. // Use a shortcut. [self continueSendElement:iq withTag:tag]; } else { // Notify all interested delegates. // This must be done serially to allow them to alter the element. GCDMulticastDelegateEnumerator *delegateEnumerator = [multicastDelegate delegateEnumerator]; dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(concurrentQueue, ^{ NSAutoreleasePool *outerPool = [[NSAutoreleasePool alloc] init]; // Allow delegates to modify outgoing element id del; dispatch_queue_t dq; while ([delegateEnumerator getNextDelegate:&del delegateQueue:&dq forSelector:selector]) { dispatch_sync(dq, ^{ NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init]; [del xmppStream:self willSendIQ:iq]; [innerPool release]; }); } dispatch_async(xmppQueue, ^{ NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init]; [self continueSendElement:iq withTag:tag]; [innerPool release]; }); [outerPool drain]; }); } } - (void)sendMessage:(XMPPMessage *)message withTag:(long)tag { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); NSAssert(state == STATE_XMPP_CONNECTED, @"Invoked with incorrect state"); // We're getting ready to send a message. // We need to notify delegates of this action to allow them to optionally alter the message element. SEL selector = @selector(xmppStream:willSendMessage:); if ([multicastDelegate countForSelector:selector] == 0) { // None of the delegates implement the method. // Use a shortcut. [self continueSendElement:message withTag:tag]; } else { // Notify all interested delegates. // This must be done serially to allow them to alter the element. GCDMulticastDelegateEnumerator *delegateEnumerator = [multicastDelegate delegateEnumerator]; dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(concurrentQueue, ^{ NSAutoreleasePool *outerPool = [[NSAutoreleasePool alloc] init]; // Allow delegates to modify outgoing element id del; dispatch_queue_t dq; while ([delegateEnumerator getNextDelegate:&del delegateQueue:&dq forSelector:selector]) { dispatch_sync(dq, ^{ NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init]; [del xmppStream:self willSendMessage:message]; [innerPool release]; }); } dispatch_async(xmppQueue, ^{ NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init]; [self continueSendElement:message withTag:tag]; [innerPool release]; }); [outerPool drain]; }); } } - (void)sendPresence:(XMPPPresence *)presence withTag:(long)tag { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); NSAssert(state == STATE_XMPP_CONNECTED, @"Invoked with incorrect state"); // We're getting ready to send a presence element. // We need to notify delegates of this action to allow them to optionally alter the presence element. SEL selector = @selector(xmppStream:willSendPresence:); if ([multicastDelegate countForSelector:selector] == 0) { // None of the delegates implement the method. // Use a shortcut. [self continueSendElement:presence withTag:tag]; } else { // Notify all interested delegates. // This must be done serially to allow them to alter the element in a thread-safe manner. GCDMulticastDelegateEnumerator *delegateEnumerator = [multicastDelegate delegateEnumerator]; dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(concurrentQueue, ^{ NSAutoreleasePool *outerPool = [[NSAutoreleasePool alloc] init]; // Allow delegates to modify outgoing element id del; dispatch_queue_t dq; while ([delegateEnumerator getNextDelegate:&del delegateQueue:&dq forSelector:selector]) { dispatch_sync(dq, ^{ NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init]; [del xmppStream:self willSendPresence:presence]; [innerPool release]; }); } dispatch_async(xmppQueue, ^{ NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init]; [self continueSendElement:presence withTag:tag]; [innerPool release]; }); [outerPool drain]; }); } } - (void)continueSendElement:(NSXMLElement *)element withTag:(long)tag { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); if (state == STATE_XMPP_CONNECTED) { NSString *outgoingStr = [element compactXMLString]; NSData *outgoingData = [outgoingStr dataUsingEncoding:NSUTF8StringEncoding]; XMPPLogSend(@"SEND: %@", outgoingStr); numberOfBytesSent += [outgoingData length]; [asyncSocket writeData:outgoingData withTimeout:TIMEOUT_XMPP_WRITE tag:tag]; if ([element isKindOfClass:[XMPPIQ class]]) { [multicastDelegate xmppStream:self didSendIQ:(XMPPIQ *)element]; } else if ([element isKindOfClass:[XMPPMessage class]]) { [multicastDelegate xmppStream:self didSendMessage:(XMPPMessage *)element]; } else if ([element isKindOfClass:[XMPPPresence class]]) { // Update myPresence if this is a normal presence element. // In other words, ignore presence subscription stuff, MUC room stuff, etc. XMPPPresence *presence = (XMPPPresence *)element; // We use the built-in [presence type] which guarantees lowercase strings, // and will return @"available" if there was no set type (as available is implicit). NSString *type = [presence type]; if ([type isEqualToString:@"available"] || [type isEqualToString:@"unavailable"]) { if ([presence toStr] == nil && myPresence != presence) { [myPresence release]; myPresence = [presence retain]; } } [multicastDelegate xmppStream:self didSendPresence:(XMPPPresence *)element]; } } } /** * Private method. * Presencts a common method for the various public sendElement methods. **/ - (void)sendElement:(NSXMLElement *)element withTag:(long)tag { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); if ([element isKindOfClass:[XMPPIQ class]]) { [self sendIQ:(XMPPIQ *)element withTag:tag]; } else if ([element isKindOfClass:[XMPPMessage class]]) { [self sendMessage:(XMPPMessage *)element withTag:tag]; } else if ([element isKindOfClass:[XMPPPresence class]]) { [self sendPresence:(XMPPPresence *)element withTag:tag]; } else { NSString *elementName = [element name]; if ([elementName isEqualToString:@"iq"]) { [self sendIQ:[XMPPIQ iqFromElement:element] withTag:tag]; } else if ([elementName isEqualToString:@"message"]) { [self sendMessage:[XMPPMessage messageFromElement:element] withTag:tag]; } else if ([elementName isEqualToString:@"presence"]) { [self sendPresence:[XMPPPresence presenceFromElement:element] withTag:tag]; } } } /** * This methods handles sending an XML fragment. * If the XMPPStream is not connected, this method does nothing. **/ - (void)sendElement:(NSXMLElement *)element { dispatch_block_t block = ^{ if (state == STATE_XMPP_CONNECTED) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self sendElement:element withTag:TAG_XMPP_WRITE_STREAM]; [pool drain]; } }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_async(xmppQueue, block); } /** * This method handles sending an XML fragment. * If the XMPPStream is not connected, this method does nothing. * * After the element has been successfully sent, * the xmppStream:didSendElementWithTag: delegate method is called. **/ - (void)sendElement:(NSXMLElement *)element andGetReceipt:(XMPPElementReceipt **)receiptPtr { if (receiptPtr == nil) { [self sendElement:element]; } else { __block XMPPElementReceipt *receipt = nil; dispatch_block_t block = ^{ if (state == STATE_XMPP_CONNECTED) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; receipt = [[XMPPElementReceipt alloc] init]; // autoreleased below [receipts addObject:receipt]; [self sendElement:element withTag:TAG_XMPP_WRITE_RECEIPT]; [pool drain]; } }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); *receiptPtr = [receipt autorelease]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Stream Negotiation //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * This method is called to start the initial negotiation process. **/ - (void)startNegotiation { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); NSAssert(![self didStartNegotiation], @"Invoked after initial negotiation has started"); XMPPLogTrace(); // Initialize the XML stream [self sendOpeningNegotiation]; // Inform delegate that the TCP connection is open, and the stream handshake has begun [multicastDelegate xmppStreamDidStartNegotiation:self]; // Initialize socket buffer if (socketBuffer == nil) { socketBuffer = [[NSMutableData alloc] initWithLength:SOCKET_BUFFER_SIZE]; } // And start reading in the server's XML stream [asyncSocket readDataWithTimeout:TIMEOUT_XMPP_READ_START buffer:socketBuffer bufferOffset:0 maxLength:[socketBuffer length] tag:TAG_XMPP_READ_START]; } /** * This method handles sending the opening <stream:stream ...> element which is needed in several situations. **/ - (void)sendOpeningNegotiation { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); if ( ![self didStartNegotiation]) { // TCP connection was just opened - We need to include the opening XML stanza NSString *s1 = @"<?xml version='1.0'?>"; NSData *outgoingData = [s1 dataUsingEncoding:NSUTF8StringEncoding]; XMPPLogSend(@"SEND: %@", s1); numberOfBytesSent += [outgoingData length]; [asyncSocket writeData:outgoingData withTimeout:TIMEOUT_XMPP_WRITE tag:TAG_XMPP_WRITE_START]; [self setDidStartNegotiation:YES]; } if (state != STATE_XMPP_CONNECTING) { XMPPLogVerbose(@"%@: Resetting parser...", THIS_FILE); // We're restarting our negotiation, so we need to reset the parser. [parser setDelegate:nil]; [parser release]; parser = [(XMPPParser *)[XMPPParser alloc] initWithDelegate:self]; } else if (parser == nil) { XMPPLogVerbose(@"%@: Initializing parser...", THIS_FILE); // Need to create parser (it was destroyed when the socket was last disconnected) parser = [(XMPPParser *)[XMPPParser alloc] initWithDelegate:self]; } else { XMPPLogVerbose(@"%@: Not touching parser...", THIS_FILE); } NSString *xmlns = @"jabber:client"; NSString *xmlns_stream = @"http://etherx.jabber.org/streams"; NSString *temp, *s2; if ([self isP2P]) { if (myJID && remoteJID) { temp = @"<stream:stream xmlns='%@' xmlns:stream='%@' version='1.0' from='%@' to='%@'>"; s2 = [NSString stringWithFormat:temp, xmlns, xmlns_stream, [myJID bare], [remoteJID bare]]; } else if (myJID) { temp = @"<stream:stream xmlns='%@' xmlns:stream='%@' version='1.0' from='%@'>"; s2 = [NSString stringWithFormat:temp, xmlns, xmlns_stream, [myJID bare]]; } else if (remoteJID) { temp = @"<stream:stream xmlns='%@' xmlns:stream='%@' version='1.0' to='%@'>"; s2 = [NSString stringWithFormat:temp, xmlns, xmlns_stream, [remoteJID bare]]; } else { temp = @"<stream:stream xmlns='%@' xmlns:stream='%@' version='1.0'>"; s2 = [NSString stringWithFormat:temp, xmlns, xmlns_stream]; } } else { if (myJID) { temp = @"<stream:stream xmlns='%@' xmlns:stream='%@' version='1.0' to='%@'>"; s2 = [NSString stringWithFormat:temp, xmlns, xmlns_stream, [myJID domain]]; } else if ([hostName length] > 0) { temp = @"<stream:stream xmlns='%@' xmlns:stream='%@' version='1.0' to='%@'>"; s2 = [NSString stringWithFormat:temp, xmlns, xmlns_stream, hostName]; } else { temp = @"<stream:stream xmlns='%@' xmlns:stream='%@' version='1.0'>"; s2 = [NSString stringWithFormat:temp, xmlns, xmlns_stream]; } } NSData *outgoingData = [s2 dataUsingEncoding:NSUTF8StringEncoding]; XMPPLogSend(@"SEND: %@", s2); numberOfBytesSent += [outgoingData length]; [asyncSocket writeData:outgoingData withTimeout:TIMEOUT_XMPP_WRITE tag:TAG_XMPP_WRITE_START]; // Update status state = STATE_XMPP_OPENING; } /** * This method handles starting TLS negotiation on the socket, using the proper settings. **/ - (void)startTLS { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); // Update state (part 2 - prompting delegates) state = STATE_XMPP_STARTTLS_2; // Create a mutable dictionary for security settings NSMutableDictionary *settings = [NSMutableDictionary dictionaryWithCapacity:5]; // Get a delegate enumerator GCDMulticastDelegateEnumerator *delegateEnumerator = [multicastDelegate delegateEnumerator]; dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(concurrentQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Prompt the delegate(s) to populate the security settings SEL selector = @selector(xmppStream:willSecureWithSettings:); id delegate; dispatch_queue_t delegateQueue; while ([delegateEnumerator getNextDelegate:&delegate delegateQueue:&delegateQueue forSelector:selector]) { dispatch_sync(delegateQueue, ^{ NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init]; [delegate xmppStream:self willSecureWithSettings:settings]; [innerPool drain]; }); } dispatch_async(xmppQueue, ^{ NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init]; [self continueStartTLS:settings]; [innerPool drain]; }); [pool drain]; }); } - (void)continueStartTLS:(NSMutableDictionary *)settings { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); XMPPLogTrace2(@"%@: %@ %@", THIS_FILE, THIS_METHOD, settings); if (state == STATE_XMPP_STARTTLS_2) { // If the delegates didn't respond if ([settings count] == 0) { // Use the default settings, and set the peer name if ([hostName length] > 0) { [settings setObject:hostName forKey:(NSString *)kCFStreamSSLPeerName]; } } [asyncSocket startTLS:settings]; [self setIsSecure:YES]; // Note: We don't need to wait for asyncSocket to complete TLS negotiation. // We can just continue reading/writing to the socket, and it will handle queueing everything for us! if ([self didStartNegotiation]) { // Now we start our negotiation over again... [self sendOpeningNegotiation]; } else { // First time starting negotiation [self startNegotiation]; } // We paused reading from the socket. // We're ready to continue now. [asyncSocket readDataWithTimeout:TIMEOUT_XMPP_READ_STREAM buffer:socketBuffer bufferOffset:0 maxLength:[socketBuffer length] tag:TAG_XMPP_READ_STREAM]; } } /** * This method is called anytime we receive the server's stream features. * This method looks at the stream features, and handles any requirements so communication can continue. **/ - (void)handleStreamFeatures { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); // Extract the stream features NSXMLElement *features = [rootElement elementForName:@"stream:features"]; // Check to see if TLS is required // Don't forget about that NSXMLElement bug you reported to apple (xmlns is required or element won't be found) NSXMLElement *f_starttls = [features elementForName:@"starttls" xmlns:@"urn:ietf:params:xml:ns:xmpp-tls"]; if (f_starttls) { if ([f_starttls elementForName:@"required"]) { // TLS is required for this connection // Update state state = STATE_XMPP_STARTTLS_1; // Send the startTLS XML request [self sendStartTLSRequest]; // We do not mark the stream as secure yet. // We're waiting to receive the <proceed/> response from the // server before we actually start the TLS handshake. // We're already listening for the response... return; } } // Check to see if resource binding is required // Don't forget about that NSXMLElement bug you reported to apple (xmlns is required or element won't be found) NSXMLElement *f_bind = [features elementForName:@"bind" xmlns:@"urn:ietf:params:xml:ns:xmpp-bind"]; if (f_bind) { // Binding is required for this connection state = STATE_XMPP_BINDING; NSString *requestedResource = [myJID resource]; if ([requestedResource length] > 0) { // Ask the server to bind the user specified resource NSXMLElement *resource = [NSXMLElement elementWithName:@"resource"]; [resource setStringValue:requestedResource]; NSXMLElement *bind = [NSXMLElement elementWithName:@"bind" xmlns:@"urn:ietf:params:xml:ns:xmpp-bind"]; [bind addChild:resource]; NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"]; [iq addAttributeWithName:@"type" stringValue:@"set"]; [iq addChild:bind]; NSString *outgoingStr = [iq compactXMLString]; NSData *outgoingData = [outgoingStr dataUsingEncoding:NSUTF8StringEncoding]; XMPPLogSend(@"SEND: %@", outgoingStr); numberOfBytesSent += [outgoingData length]; [asyncSocket writeData:outgoingData withTimeout:TIMEOUT_XMPP_WRITE tag:TAG_XMPP_WRITE_STREAM]; } else { // The user didn't specify a resource, so we ask the server to bind one for us NSXMLElement *bind = [NSXMLElement elementWithName:@"bind" xmlns:@"urn:ietf:params:xml:ns:xmpp-bind"]; NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"]; [iq addAttributeWithName:@"type" stringValue:@"set"]; [iq addChild:bind]; NSString *outgoingStr = [iq compactXMLString]; NSData *outgoingData = [outgoingStr dataUsingEncoding:NSUTF8StringEncoding]; XMPPLogSend(@"SEND: %@", outgoingStr); numberOfBytesSent += [outgoingData length]; [asyncSocket writeData:outgoingData withTimeout:TIMEOUT_XMPP_WRITE tag:TAG_XMPP_WRITE_STREAM]; } // We're already listening for the response... return; } // It looks like all has gone well, and the connection should be ready to use now state = STATE_XMPP_CONNECTED; if (![self isAuthenticated]) { [self setupKeepAliveTimer]; // Notify delegates [multicastDelegate xmppStreamDidConnect:self]; } } - (void)handleStartTLSResponse:(NSXMLElement *)response { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); // We're expecting a proceed response // If we get anything else we can safely assume it's the equivalent of a failure response if ( ![[response name] isEqualToString:@"proceed"]) { // We can close our TCP connection now [self disconnect]; // The socketDidDisconnect:withError: method will handle everything else return; } // Start TLS negotiation [self startTLS]; } /** * After the registerUser:withPassword: method is invoked, a registration message is sent to the server. * We're waiting for the result from this registration request. **/ - (void)handleRegistration:(NSXMLElement *)response { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); if ([[response attributeStringValueForName:@"type"] isEqualToString:@"error"]) { // Revert back to connected state (from authenticating state) state = STATE_XMPP_CONNECTED; [multicastDelegate xmppStream:self didNotRegister:response]; } else { // Revert back to connected state (from authenticating state) state = STATE_XMPP_CONNECTED; [multicastDelegate xmppStreamDidRegister:self]; } } /** * After the authenticateUser:withPassword:resource method is invoked, a authentication message is sent to the server. * If the server supports digest-md5 sasl authentication, it is used. Otherwise plain sasl authentication is used, * assuming the server supports it. * * Now if digest-md5 was used, we sent a challenge request, and we're waiting for a challenge response. * If plain sasl was used, we sent our authentication information, and we're waiting for a success response. **/ - (void)handleAuth1:(NSXMLElement *)response { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); if ([self supportsDigestMD5Authentication]) { // We're expecting a challenge response // If we get anything else we can safely assume it's the equivalent of a failure response if ( ![[response name] isEqualToString:@"challenge"]) { // Revert back to connected state (from authenticating state) state = STATE_XMPP_CONNECTED; [multicastDelegate xmppStream:self didNotAuthenticate:response]; } else { // Create authentication object from the given challenge // We'll release this object at the end of this else block XMPPDigestAuthentication *auth = [[XMPPDigestAuthentication alloc] initWithChallenge:response]; NSString *virtualHostName = [myJID domain]; NSString *serverHostName = hostName; // Sometimes the realm isn't specified // In this case I believe the realm is implied as the virtual host name if (![auth realm]) { if([virtualHostName length] > 0) [auth setRealm:virtualHostName]; else [auth setRealm:serverHostName]; } // Set digest-uri if([virtualHostName length] > 0) [auth setDigestURI:[NSString stringWithFormat:@"xmpp/%@", virtualHostName]]; else [auth setDigestURI:[NSString stringWithFormat:@"xmpp/%@", serverHostName]]; // Set username and password [auth setUsername:[myJID user] password:tempPassword]; // Create and send challenge response element NSXMLElement *cr = [NSXMLElement elementWithName:@"response" xmlns:@"urn:ietf:params:xml:ns:xmpp-sasl"]; [cr setStringValue:[auth base64EncodedFullResponse]]; NSString *outgoingStr = [cr compactXMLString]; NSData *outgoingData = [outgoingStr dataUsingEncoding:NSUTF8StringEncoding]; XMPPLogSend(@"SEND: %@", outgoingStr); numberOfBytesSent += [outgoingData length]; [asyncSocket writeData:outgoingData withTimeout:TIMEOUT_XMPP_WRITE tag:TAG_XMPP_WRITE_STREAM]; // Release unneeded resources [auth release]; [tempPassword release]; tempPassword = nil; // Update state state = STATE_XMPP_AUTH_2; } } else if ([self supportsPlainAuthentication]) { // We're expecting a success response // If we get anything else we can safely assume it's the equivalent of a failure response if ( ![[response name] isEqualToString:@"success"]) { // Revert back to connected state (from authenticating state) state = STATE_XMPP_CONNECTED; [multicastDelegate xmppStream:self didNotAuthenticate:response]; } else { // We are successfully authenticated (via sasl:plain) [self setIsAuthenticated:YES]; // Now we start our negotiation over again... [self sendOpeningNegotiation]; } } else { // We used the old fashioned jabber:iq:auth mechanism if ([[response attributeStringValueForName:@"type"] isEqualToString:@"error"]) { // Revert back to connected state (from authenticating state) state = STATE_XMPP_CONNECTED; [multicastDelegate xmppStream:self didNotAuthenticate:response]; } else { // We are successfully authenticated (via non-sasl:digest) // And we've binded our resource as well [self setIsAuthenticated:YES]; // Revert back to connected state (from authenticating state) state = STATE_XMPP_CONNECTED; [multicastDelegate xmppStreamDidAuthenticate:self]; } } } /** * This method handles the result of our challenge response we sent in handleAuth1 using digest-md5 sasl. **/ - (void)handleAuth2:(NSXMLElement *)response { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); if ([[response name] isEqualToString:@"challenge"]) { XMPPDigestAuthentication *auth = [[[XMPPDigestAuthentication alloc] initWithChallenge:response] autorelease]; if(![auth rspauth]) { // We're getting another challenge??? // I'm not sure what this could possibly be, so for now I'll assume it's a failure // Revert back to connected state (from authenticating state) state = STATE_XMPP_CONNECTED; [multicastDelegate xmppStream:self didNotAuthenticate:response]; } else { // We received another challenge, but it's really just an rspauth // This is supposed to be included in the success element (according to the updated RFC) // but many implementations incorrectly send it inside a second challenge request. // Create and send empty challenge response element NSXMLElement *cr = [NSXMLElement elementWithName:@"response" xmlns:@"urn:ietf:params:xml:ns:xmpp-sasl"]; NSString *outgoingStr = [cr compactXMLString]; NSData *outgoingData = [outgoingStr dataUsingEncoding:NSUTF8StringEncoding]; XMPPLogSend(@"SEND: %@", outgoingStr); numberOfBytesSent += [outgoingData length]; [asyncSocket writeData:outgoingData withTimeout:TIMEOUT_XMPP_WRITE tag:TAG_XMPP_WRITE_STREAM]; // The state remains in STATE_XMPP_AUTH_2 } } else if ([[response name] isEqualToString:@"success"]) { // We are successfully authenticated (via sasl:digest-md5) [self setIsAuthenticated:YES]; // Now we start our negotiation over again... [self sendOpeningNegotiation]; } else { // We received some kind of <failure/> element // Revert back to connected state (from authenticating state) state = STATE_XMPP_CONNECTED; [multicastDelegate xmppStream:self didNotAuthenticate:response]; } } /** * This method handles the result of our SASL Anonymous Authentication challenge **/ - (void)handleAuth3:(NSXMLElement *)response { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); // We're expecting a success response // If we get anything else we can safely assume it's the equivalent of a failure response if ( ![[response name] isEqualToString:@"success"]) { // Revert back to connected state (from authenticating state) state = STATE_XMPP_CONNECTED; [multicastDelegate xmppStream:self didNotAuthenticate:response]; } else { // We are successfully authenticated (via sasl:x-facebook-platform or sasl:plain) [self setIsAuthenticated:YES]; // Now we start our negotiation over again... [self sendOpeningNegotiation]; } } - (void)handleBinding:(NSXMLElement *)response { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); NSXMLElement *r_bind = [response elementForName:@"bind" xmlns:@"urn:ietf:params:xml:ns:xmpp-bind"]; NSXMLElement *r_jid = [r_bind elementForName:@"jid"]; if (r_jid) { // We're properly binded to a resource now // Extract and save our resource (it may not be what we originally requested) NSString *fullJIDStr = [r_jid stringValue]; [self setMyJID:[XMPPJID jidWithString:fullJIDStr]]; // And we may now have to do one last thing before we're ready - start an IM session NSXMLElement *features = [rootElement elementForName:@"stream:features"]; // Check to see if a session is required // Don't forget about that NSXMLElement bug you reported to apple (xmlns is required or element won't be found) NSXMLElement *f_session = [features elementForName:@"session" xmlns:@"urn:ietf:params:xml:ns:xmpp-session"]; if (f_session) { NSXMLElement *session = [NSXMLElement elementWithName:@"session"]; [session setXmlns:@"urn:ietf:params:xml:ns:xmpp-session"]; NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"]; [iq addAttributeWithName:@"type" stringValue:@"set"]; [iq addChild:session]; NSString *outgoingStr = [iq compactXMLString]; NSData *outgoingData = [outgoingStr dataUsingEncoding:NSUTF8StringEncoding]; XMPPLogSend(@"SEND: %@", outgoingStr); numberOfBytesSent += [outgoingData length]; [asyncSocket writeData:outgoingData withTimeout:TIMEOUT_XMPP_WRITE tag:TAG_XMPP_WRITE_STREAM]; // Update state state = STATE_XMPP_START_SESSION; } else { // Revert back to connected state (from binding state) state = STATE_XMPP_CONNECTED; [multicastDelegate xmppStreamDidAuthenticate:self]; } } else { // It appears the server didn't allow our resource choice // We'll simply let the server choose then NSXMLElement *bind = [NSXMLElement elementWithName:@"bind" xmlns:@"urn:ietf:params:xml:ns:xmpp-bind"]; NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"]; [iq addAttributeWithName:@"type" stringValue:@"set"]; [iq addChild:bind]; NSString *outgoingStr = [iq compactXMLString]; NSData *outgoingData = [outgoingStr dataUsingEncoding:NSUTF8StringEncoding]; XMPPLogSend(@"SEND: %@", outgoingStr); numberOfBytesSent += [outgoingData length]; [asyncSocket writeData:outgoingData withTimeout:TIMEOUT_XMPP_WRITE tag:TAG_XMPP_WRITE_STREAM]; // The state remains in STATE_XMPP_BINDING } } - (void)handleStartSessionResponse:(NSXMLElement *)response { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); if ([[response attributeStringValueForName:@"type"] isEqualToString:@"result"]) { // Revert back to connected state (from start session state) state = STATE_XMPP_CONNECTED; [multicastDelegate xmppStreamDidAuthenticate:self]; } else { // Revert back to connected state (from start session state) state = STATE_XMPP_CONNECTED; [multicastDelegate xmppStream:self didNotAuthenticate:response]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPSRVResolver Delegate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)tryNextSrvResult { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); NSError *connectError = nil; BOOL success = NO; while (srvResultsIndex < [srvResults count]) { XMPPSRVRecord *srvRecord = [srvResults objectAtIndex:srvResultsIndex]; NSString *srvHost = srvRecord.target; UInt16 srvPort = srvRecord.port; success = [self connectToHost:srvHost onPort:srvPort error:&connectError]; if (success) { break; } else { srvResultsIndex++; } } if (!success) { // SRV resolution of the JID domain failed. // As per the RFC: // // "If the SRV lookup fails, the fallback is a normal IPv4/IPv6 address record resolution // to determine the IP address, using the "xmpp-client" port 5222, registered with the IANA." // // In other words, just try connecting to the domain specified in the JID. success = [self connectToHost:[myJID domain] onPort:5222 error:&connectError]; } if (!success) { state = STATE_XMPP_DISCONNECTED; [multicastDelegate xmppStreamDidDisconnect:self withError:connectError]; } } - (void)srvResolver:(XMPPSRVResolver *)sender didResolveRecords:(NSArray *)records { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); if (sender != srvResolver) return; XMPPLogTrace(); srvResults = [records copy]; srvResultsIndex = 0; state = STATE_XMPP_CONNECTING; [self tryNextSrvResult]; } - (void)srvResolver:(XMPPSRVResolver *)sender didNotResolveDueToError:(NSError *)error { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); if (sender != srvResolver) return; XMPPLogTrace(); state = STATE_XMPP_CONNECTING; [self tryNextSrvResult]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark AsyncSocket Delegate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Called when a socket connects and is ready for reading and writing. "host" will be an IP address, not a DNS name. **/ - (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port { // This method is invoked on the xmppQueue. // // The TCP connection is now established. XMPPLogTrace(); #if TARGET_OS_IPHONE { if (self.enableBackgroundingOnSocket) { __block BOOL result; [asyncSocket performBlock:^{ result = [asyncSocket enableBackgroundingOnSocket]; }]; if (result) XMPPLogVerbose(@"%@: Enabled backgrounding on socket", THIS_FILE); else XMPPLogError(@"%@: Error enabling backgrounding on socket!", THIS_FILE); } } #endif [multicastDelegate xmppStream:self socketDidConnect:sock]; [srvResolver release]; srvResolver = nil; [srvResults release]; srvResults = nil; // Are we using old-style SSL? (Not the upgrade to TLS technique specified in the XMPP RFC) if ([self isSecure]) { // The connection must be secured immediately (just like with HTTPS) [self startTLS]; } else { [self startNegotiation]; } } - (void)socketDidSecure:(GCDAsyncSocket *)sock { // This method is invoked on the xmppQueue. XMPPLogTrace(); [multicastDelegate xmppStreamDidSecure:self]; } /** * Called when a socket has completed reading the requested data. Not called if there is an error. **/ - (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag { // This method is invoked on the xmppQueue. XMPPLogTrace(); lastSendReceiveTime = dispatch_time(DISPATCH_TIME_NOW, 0); if (XMPP_LOG_RECV_PRE) { NSString *dataAsStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; XMPPLogRecvPre(@"RECV: %@", dataAsStr); [dataAsStr release]; } numberOfBytesReceived += [data length]; dispatch_async(parserQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [parser parseData:data]; dispatch_async(xmppQueue, ^{ NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init]; // Continue reading for XML elements. if (state == STATE_XMPP_OPENING) { [asyncSocket readDataWithTimeout:TIMEOUT_XMPP_READ_START buffer:socketBuffer bufferOffset:0 maxLength:[socketBuffer length] tag:TAG_XMPP_READ_START]; } else if (state != STATE_XMPP_STARTTLS_2) { [asyncSocket readDataWithTimeout:TIMEOUT_XMPP_READ_STREAM buffer:socketBuffer bufferOffset:0 maxLength:[socketBuffer length] tag:TAG_XMPP_READ_STREAM]; } [innerPool drain]; }); [pool drain]; }); } /** * Called after data with the given tag has been successfully sent. **/ - (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag { // This method is invoked on the xmppQueue. XMPPLogTrace(); lastSendReceiveTime = dispatch_time(DISPATCH_TIME_NOW, 0); if (tag == TAG_XMPP_WRITE_RECEIPT) { if ([receipts count] == 0) { XMPPLogWarn(@"%@: Found TAG_XMPP_WRITE_RECEIPT with no pending receipts!", THIS_FILE); return; } XMPPElementReceipt *receipt = [receipts objectAtIndex:0]; [receipt signalSuccess]; [receipts removeObjectAtIndex:0]; } } /** * Called when a socket disconnects with or without error. **/ - (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err { // This method is invoked on the xmppQueue. XMPPLogTrace(); if (srvResults && (++srvResultsIndex < [srvResults count])) { [self tryNextSrvResult]; } else { // Update state state = STATE_XMPP_DISCONNECTED; // Release socket buffer [socketBuffer release]; socketBuffer = nil; // Release the parser (to free underlying resources) [parser setDelegate:nil]; [parser release]; parser = nil; // Clear any saved authentication information [tempPassword release]; tempPassword = nil; // Clear stored elements [myPresence release]; myPresence = nil; [rootElement release]; rootElement = nil; // Stop the keep alive timer if (keepAliveTimer) { dispatch_source_cancel(keepAliveTimer); keepAliveTimer = NULL; } // Clear srv results [srvResolver release]; srvResolver = nil; [srvResults release]; srvResults = nil; // Clear any pending receipts for (XMPPElementReceipt *receipt in receipts) { [receipt signalFailure]; } [receipts removeAllObjects]; // Clear flags flags = 0; // Notify delegate if (parserError) { [multicastDelegate xmppStreamDidDisconnect:self withError:parserError]; [parserError release]; parserError = nil; } else { [multicastDelegate xmppStreamDidDisconnect:self withError:err]; } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPParser Delegate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Called when the xmpp parser has read in the entire root element. **/ - (void)xmppParser:(XMPPParser *)sender didReadRoot:(NSXMLElement *)root { NSAssert(dispatch_get_current_queue() == parserQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); dispatch_async(xmppQueue, ^{ if (sender != parser) return_from_block; NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPLogRecvPost(@"RECV: %@", [root compactXMLString]); // At this point we've sent our XML stream header, and we've received the response XML stream header. // We save the root element of our stream for future reference. // Digest Access authentication requires us to know the ID attribute from the <stream:stream/> element. [rootElement release]; rootElement = [root retain]; if ([self isP2P]) { // XEP-0174 specifies that <stream:features/> SHOULD be sent by the receiver. // In other words, if we're the recipient we will now send our features. // But if we're the initiator, we can't depend on receiving their features. // Either way, we're connected at this point. state = STATE_XMPP_CONNECTED; if ([self isP2PRecipient]) { // Extract the remoteJID: // // <stream:stream ... from='<remoteJID>' to='<myJID>'> NSString *from = [[rootElement attributeForName:@"from"] stringValue]; remoteJID = [[XMPPJID jidWithString:from] retain]; // Send our stream features. // To do so we need to ask the delegate to fill it out for us. NSXMLElement *streamFeatures = [NSXMLElement elementWithName:@"stream:features"]; [multicastDelegate xmppStream:self willSendP2PFeatures:streamFeatures]; NSString *outgoingStr = [streamFeatures compactXMLString]; NSData *outgoingData = [outgoingStr dataUsingEncoding:NSUTF8StringEncoding]; XMPPLogSend(@"SEND: %@", outgoingStr); numberOfBytesSent += [outgoingData length]; [asyncSocket writeData:outgoingData withTimeout:TIMEOUT_XMPP_WRITE tag:TAG_XMPP_WRITE_STREAM]; } // Make sure the delegate didn't disconnect us in the xmppStream:willSendP2PFeatures: method. if ([self isConnected]) { [multicastDelegate xmppStreamDidConnect:self]; } } else { // Check for RFC compliance if ([self serverXmppStreamVersionNumber] >= 1.0) { // Update state - we're now onto stream negotiations state = STATE_XMPP_NEGOTIATING; // Note: We're waiting for the <stream:features> now } else { // The server isn't RFC comliant, and won't be sending any stream features. // We would still like to know what authentication features it supports though, // so we'll use the jabber:iq:auth namespace, which was used prior to the RFC spec. // Update state - we're onto psuedo negotiation state = STATE_XMPP_NEGOTIATING; NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:auth"]; NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"]; [iq addAttributeWithName:@"type" stringValue:@"get"]; [iq addChild:query]; NSString *outgoingStr = [iq compactXMLString]; NSData *outgoingData = [outgoingStr dataUsingEncoding:NSUTF8StringEncoding]; XMPPLogSend(@"SEND: %@", outgoingStr); numberOfBytesSent += [outgoingData length]; [asyncSocket writeData:outgoingData withTimeout:TIMEOUT_XMPP_WRITE tag:TAG_XMPP_WRITE_STREAM]; // Now wait for the response IQ } } [pool drain]; }); } - (void)xmppParser:(XMPPParser *)sender didReadElement:(NSXMLElement *)element { NSAssert(dispatch_get_current_queue() == parserQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); dispatch_async(xmppQueue, ^{ if (sender != parser) return_from_block; NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPLogRecvPost(@"RECV: %@", [element compactXMLString]); NSString *elementName = [element name]; if ([elementName isEqualToString:@"stream:error"] || [elementName isEqualToString:@"error"]) { [multicastDelegate xmppStream:self didReceiveError:element]; [pool drain]; return; } if (state == STATE_XMPP_NEGOTIATING) { // We've just read in the stream features // We consider this part of the root element, so we'll add it (replacing any previously sent features) [rootElement setChildren:[NSArray arrayWithObject:element]]; // Call a method to handle any requirements set forth in the features [self handleStreamFeatures]; } else if (state == STATE_XMPP_STARTTLS_1) { // The response from our starttls message [self handleStartTLSResponse:element]; } else if (state == STATE_XMPP_REGISTERING) { // The iq response from our registration request [self handleRegistration:element]; } else if (state == STATE_XMPP_AUTH_1) { // The challenge response from our auth message [self handleAuth1:element]; } else if (state == STATE_XMPP_AUTH_2) { // The response from our challenge response [self handleAuth2:element]; } else if (state == STATE_XMPP_AUTH_3) { // The response from our x-facebook-platform or authenticateAnonymously challenge [self handleAuth3:element]; } else if (state == STATE_XMPP_BINDING) { // The response from our binding request [self handleBinding:element]; } else if (state == STATE_XMPP_START_SESSION) { // The response from our start session request [self handleStartSessionResponse:element]; } else { if ([elementName isEqualToString:@"iq"]) { XMPPIQ *iq = [XMPPIQ iqFromElement:element]; // Notify all interested delegates about the received IQ. // Keep track of whether the delegates respond to the IQ. GCDMulticastDelegateEnumerator *delegateEnumerator = [multicastDelegate delegateEnumerator]; id del; dispatch_queue_t dq; SEL selector = @selector(xmppStream:didReceiveIQ:); dispatch_semaphore_t delSemaphore = dispatch_semaphore_create(0); dispatch_group_t delGroup = dispatch_group_create(); while ([delegateEnumerator getNextDelegate:&del delegateQueue:&dq forSelector:selector]) { dispatch_group_async(delGroup, dq, ^{ NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init]; if ([del xmppStream:self didReceiveIQ:iq]) { dispatch_semaphore_signal(delSemaphore); } [innerPool release]; }); } dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(concurrentQueue, ^{ NSAutoreleasePool *outerPool = [[NSAutoreleasePool alloc] init]; dispatch_group_wait(delGroup, DISPATCH_TIME_FOREVER); // Did any of the delegates respond to the IQ? BOOL responded = (dispatch_semaphore_wait(delSemaphore, DISPATCH_TIME_NOW) == 0); // An entity that receives an IQ request of type "get" or "set" MUST reply // with an IQ response of type "result" or "error". // // The response MUST preserve the 'id' attribute of the request. if (!responded && [iq requiresResponse]) { // Return error message: // // <iq to="jid" type="error" id="id"> // <query xmlns="ns"/> // <error type="cancel" code="501"> // <feature-not-implemented xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/> // </error> // </iq> NSXMLElement *reason = [NSXMLElement elementWithName:@"feature-not-implemented" xmlns:@"urn:ietf:params:xml:ns:xmpp-stanzas"]; NSXMLElement *error = [NSXMLElement elementWithName:@"error"]; [error addAttributeWithName:@"type" stringValue:@"cancel"]; [error addAttributeWithName:@"code" stringValue:@"501"]; [error addChild:reason]; XMPPIQ *iqResponse = [XMPPIQ iqWithType:@"error" to:[iq from] elementID:[iq elementID] child:error]; NSXMLElement *iqChild = [iq childElement]; if (iqChild) { NSXMLNode *iqChildCopy = [iqChild copy]; [iqResponse insertChild:iqChildCopy atIndex:0]; [iqChildCopy release]; } // Purposefully go through the sendElement: method // so that it gets dispatched onto the xmppQueue, // and so that modules may get notified of the outgoing error message. [self sendElement:iqResponse]; } dispatch_release(delSemaphore); dispatch_release(delGroup); [outerPool drain]; }); } else if ([elementName isEqualToString:@"message"]) { [multicastDelegate xmppStream:self didReceiveMessage:[XMPPMessage messageFromElement:element]]; } else if ([elementName isEqualToString:@"presence"]) { [multicastDelegate xmppStream:self didReceivePresence:[XMPPPresence presenceFromElement:element]]; } else if ([self isP2P] && ([elementName isEqualToString:@"stream:features"] || [elementName isEqualToString:@"features"])) { [multicastDelegate xmppStream:self didReceiveP2PFeatures:element]; } else { [multicastDelegate xmppStream:self didReceiveError:element]; } } [pool drain]; }); } - (void)xmppParserDidEnd:(XMPPParser *)sender { NSAssert(dispatch_get_current_queue() == parserQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); dispatch_async(xmppQueue, ^{ if (sender != parser) return_from_block; NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [asyncSocket disconnect]; [pool drain]; }); } - (void)xmppParser:(XMPPParser *)sender didFail:(NSError *)error { NSAssert(dispatch_get_current_queue() == parserQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); dispatch_async(xmppQueue, ^{ if (sender != parser) return_from_block; NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [parserError release]; parserError = [error retain]; [asyncSocket disconnect]; [pool drain]; }); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Keep Alive //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)setupKeepAliveTimer { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); if (keepAliveTimer) { dispatch_source_cancel(keepAliveTimer); keepAliveTimer = NULL; } if (state == STATE_XMPP_CONNECTED) { if (keepAliveInterval > 0) { keepAliveTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, xmppQueue); dispatch_source_set_event_handler(keepAliveTimer, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self keepAlive]; [pool drain]; }); dispatch_source_t theKeepAliveTimer = keepAliveTimer; dispatch_source_set_cancel_handler(keepAliveTimer, ^{ XMPPLogVerbose(@"dispatch_release(keepAliveTimer)"); dispatch_release(theKeepAliveTimer); }); // Everytime we send or receive data, we update our lastSendReceiveTime. // We set our timer to fire several times per keepAliveInterval. // This allows us to maintain a single timer, // and an acceptable timer resolution (assuming larger keepAliveIntervals). NSTimeInterval interval = keepAliveInterval / 4.0; dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (interval * NSEC_PER_SEC)); dispatch_source_set_timer(keepAliveTimer, tt, DISPATCH_TIME_FOREVER, 1.0); dispatch_resume(keepAliveTimer); } } } - (void)keepAlive { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); if (state == STATE_XMPP_CONNECTED) { dispatch_time_t now = dispatch_time(DISPATCH_TIME_NOW, 0); NSTimeInterval elapsed = ((now - lastSendReceiveTime) / NSEC_PER_SEC); if (elapsed >= keepAliveInterval) { NSData *outgoingData = [@" " dataUsingEncoding:NSUTF8StringEncoding]; numberOfBytesSent += [outgoingData length]; [asyncSocket writeData:outgoingData withTimeout:TIMEOUT_XMPP_WRITE tag:TAG_XMPP_WRITE_STREAM]; // Force update the lastSendReceiveTime here just to be safe. // // In case the TCP socket comes to a crawl with a giant element in the queue, // which would prevent the socket:didWriteDataWithTag: method from being called for some time. lastSendReceiveTime = now; } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Module Plug-In System //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)registerModule:(XMPPModule *)module { if (module == nil) return; // Asynchronous operation dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Register module [registeredModules add:module]; // Add auto delegates (if there are any) NSString *className = NSStringFromClass([module class]); GCDMulticastDelegate *autoDelegates = [autoDelegateDict objectForKey:className]; GCDMulticastDelegateEnumerator *autoDelegatesEnumerator = [autoDelegates delegateEnumerator]; id delegate; dispatch_queue_t delegateQueue; while ([autoDelegatesEnumerator getNextDelegate:&delegate delegateQueue:&delegateQueue]) { [module addDelegate:delegate delegateQueue:delegateQueue]; } // Notify our own delegate(s) [multicastDelegate xmppStream:self didRegisterModule:module]; [pool drain]; }; // Asynchronous operation if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_async(xmppQueue, block); } - (void)unregisterModule:(XMPPModule *)module { if (module == nil) return; // Synchronous operation dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Notify our own delegate(s) [multicastDelegate xmppStream:self willUnregisterModule:module]; // Remove auto delegates (if there are any) NSString *className = NSStringFromClass([module class]); GCDMulticastDelegate *autoDelegates = [autoDelegateDict objectForKey:className]; GCDMulticastDelegateEnumerator *autoDelegatesEnumerator = [autoDelegates delegateEnumerator]; id delegate; dispatch_queue_t delegateQueue; while ([autoDelegatesEnumerator getNextDelegate:&delegate delegateQueue:&delegateQueue]) { [module removeDelegate:delegate delegateQueue:delegateQueue]; } // Unregister modules [registeredModules remove:module]; [pool drain]; }; // Synchronous operation if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); } - (void)autoAddDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue toModulesOfClass:(Class)aClass { if (delegate == nil) return; if (aClass == nil) return; // Asynchronous operation dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSString *className = NSStringFromClass(aClass); // Add the delegate to all currently registered modules of the given class. DDListEnumerator *registeredModulesEnumerator = [registeredModules listEnumerator]; XMPPModule *module; while ((module = (XMPPModule *)[registeredModulesEnumerator nextElement])) { if ([module isKindOfClass:aClass]) { [module addDelegate:delegate delegateQueue:delegateQueue]; } } // Add the delegate to list of auto delegates for the given class. // It will be added as a delegate to future registered modules of the given class. id delegates = [autoDelegateDict objectForKey:className]; if (delegates == nil) { delegates = [[[GCDMulticastDelegate alloc] init] autorelease]; [autoDelegateDict setObject:delegates forKey:className]; } [delegates addDelegate:delegate delegateQueue:delegateQueue]; [pool drain]; }; // Asynchronous operation if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_async(xmppQueue, block); } - (void)removeAutoDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue fromModulesOfClass:(Class)aClass { if (delegate == nil) return; // delegateQueue may be NULL // aClass may be NULL // Synchronous operation dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if (aClass == NULL) { // Remove the delegate from all currently registered modules of ANY class. DDListEnumerator *registeredModulesEnumerator = [registeredModules listEnumerator]; XMPPModule *module; while ((module = (XMPPModule *)[registeredModulesEnumerator nextElement])) { [module removeDelegate:delegate delegateQueue:delegateQueue]; } // Remove the delegate from list of auto delegates for all classes, // so that it will not be auto added as a delegate to future registered modules. for (GCDMulticastDelegate *delegates in [autoDelegateDict objectEnumerator]) { [delegates removeDelegate:delegate delegateQueue:delegateQueue]; } } else { NSString *className = NSStringFromClass(aClass); // Remove the delegate from all currently registered modules of the given class. DDListEnumerator *registeredModulesEnumerator = [registeredModules listEnumerator]; XMPPModule *module; while ((module = (XMPPModule *)[registeredModulesEnumerator nextElement])) { if ([module isKindOfClass:aClass]) { [module removeDelegate:delegate delegateQueue:delegateQueue]; } } // Remove the delegate from list of auto delegates for the given class, // so that it will not be added as a delegate to future registered modules of the given class. GCDMulticastDelegate *delegates = [autoDelegateDict objectForKey:className]; [delegates removeDelegate:delegate delegateQueue:delegateQueue]; } [pool drain]; }; // Synchronous operation if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); } - (void)enumerateModulesWithBlock:(void (^)(XMPPModule *module, NSUInteger idx, BOOL *stop))enumBlock { if (enumBlock == NULL) return; dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; DDListEnumerator *registeredModulesEnumerator = [registeredModules listEnumerator]; XMPPModule *module; NSUInteger i = 0; BOOL stop = NO; while ((module = (XMPPModule *)[registeredModulesEnumerator nextElement])) { enumBlock(module, i, &stop); if (stop) break; else i++; } [pool drain]; }; // Synchronous operation if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Utilities //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + (NSString *)generateUUID { NSString *result = nil; CFUUIDRef uuid = CFUUIDCreate(NULL); if (uuid) { result = NSMakeCollectable(CFUUIDCreateString(NULL, uuid)); CFRelease(uuid); } return [result autorelease]; } - (NSString *)generateUUID { return [[self class] generateUUID]; } - (NSThread *)xmppUtilityThread { // This is a read-only variable, set in the init method and never altered. // Thus we supply direct access to it in this method. return xmppUtilityThread; } - (NSRunLoop *)xmppUtilityRunLoop { __block NSRunLoop *result; dispatch_block_t block = ^{ result = [xmppUtilityRunLoop retain]; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); return [result autorelease]; } - (void)setXmppUtilityRunLoop:(NSRunLoop *)runLoop { dispatch_async(xmppQueue, ^{ if (xmppUtilityRunLoop == nil) { xmppUtilityRunLoop = [runLoop retain]; } }); } + (void)xmppThreadMain { // This is the xmppUtilityThread. // It is designed to be used only if absolutely necessary. // If there is a GCD alternative, it should be used instead. NSAutoreleasePool *outerPool = [[NSAutoreleasePool alloc] init]; // Set XMPPStream's xmppUtilityRunLoop variable. // // And when done, remove the xmppStream reference from the dictionary so it's no longer retained. XMPPStream *creator = [[[NSThread currentThread] threadDictionary] objectForKey:@"XMPPStream"]; [creator setXmppUtilityRunLoop:[NSRunLoop currentRunLoop]]; [[[NSThread currentThread] threadDictionary] removeObjectForKey:@"XMPPStream"]; // We can't iteratively run the run loop unless it has at least one source or timer. // So we'll create a timer that will probably never fire. [NSTimer scheduledTimerWithTimeInterval:DBL_MAX target:self selector:@selector(xmppThreadIgnore:) userInfo:nil repeats:YES]; BOOL isCancelled = NO; BOOL hasRunLoopSources = YES; while (!isCancelled && hasRunLoopSources) { NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init]; hasRunLoopSources = [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; isCancelled = [[NSThread currentThread] isCancelled]; [innerPool drain]; } [outerPool drain]; } + (void)xmppThreadStop { [[NSThread currentThread] cancel]; } + (void)xmppThreadIgnore:(NSTimer *)aTimer { // Ignore } @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation XMPPElementReceipt - (id)init { if ((self = [super init])) { atomicFlags = 0; semaphore = dispatch_semaphore_create(0); } return self; } - (void)signalSuccess { uint32_t mask = 3; OSAtomicOr32Barrier(mask, &atomicFlags); dispatch_semaphore_signal(semaphore); } - (void)signalFailure { uint32_t mask = 1; OSAtomicOr32Barrier(mask, &atomicFlags); dispatch_semaphore_signal(semaphore); } - (BOOL)wait:(NSTimeInterval)timeout_seconds { uint32_t mask = 0; uint32_t flags = OSAtomicOr32Barrier(mask, &atomicFlags); if (flags > 0) return (flags > 1); dispatch_time_t timeout_nanos; if (timeout_seconds < 0.0) timeout_nanos = DISPATCH_TIME_NOW; else timeout_nanos = dispatch_time(DISPATCH_TIME_NOW, (timeout_seconds * NSEC_PER_SEC)); // dispatch_semaphore_wait // // Decrement the counting semaphore. If the resulting value is less than zero, // this function waits in FIFO order for a signal to occur before returning. // // Returns zero on success, or non-zero if the timeout occurred. // // Note: If the timeout occurs, the semaphore value is incremented (without signaling). long result = dispatch_semaphore_wait(semaphore, timeout_nanos); if (result == 0) { flags = OSAtomicOr32Barrier(mask, &atomicFlags); return (flags > 1); } else { return NO; } } - (void)dealloc { dispatch_release(semaphore); [super dealloc]; } @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation XMPPDigestAuthentication - (id)initWithChallenge:(NSXMLElement *)challenge { if((self = [super init])) { // Convert the base 64 encoded data into a string NSData *base64Data = [[challenge stringValue] dataUsingEncoding:NSASCIIStringEncoding]; NSData *decodedData = [base64Data base64Decoded]; NSString *authStr = [[[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding] autorelease]; XMPPLogVerbose(@"%@: Decoded challenge: %@", THIS_FILE, authStr); // Extract all the key=value pairs, and put them in a dictionary for easy lookup NSMutableDictionary *auth = [NSMutableDictionary dictionaryWithCapacity:5]; NSArray *components = [authStr componentsSeparatedByString:@","]; int i; for(i = 0; i < [components count]; i++) { NSString *component = [components objectAtIndex:i]; NSRange separator = [component rangeOfString:@"="]; if(separator.location != NSNotFound) { NSMutableString *key = [[component substringToIndex:separator.location] mutableCopy]; NSMutableString *value = [[component substringFromIndex:separator.location+1] mutableCopy]; if(key) CFStringTrimWhitespace((CFMutableStringRef)key); if(value) CFStringTrimWhitespace((CFMutableStringRef)value); if([value hasPrefix:@"\""] && [value hasSuffix:@"\""] && [value length] > 2) { // Strip quotes from value [value deleteCharactersInRange:NSMakeRange(0, 1)]; [value deleteCharactersInRange:NSMakeRange([value length]-1, 1)]; } [auth setObject:value forKey:key]; [value release]; [key release]; } } // Extract and retain the elements we need rspauth = [[auth objectForKey:@"rspauth"] copy]; realm = [[auth objectForKey:@"realm"] copy]; nonce = [[auth objectForKey:@"nonce"] copy]; qop = [[auth objectForKey:@"qop"] copy]; // Generate cnonce cnonce = [[XMPPStream generateUUID] retain]; } return self; } - (void)dealloc { [rspauth release]; [realm release]; [nonce release]; [qop release]; [username release]; [password release]; [cnonce release]; [nc release]; [digestURI release]; [super dealloc]; } - (NSString *)rspauth { return [[rspauth copy] autorelease]; } - (NSString *)realm { return [[realm copy] autorelease]; } - (void)setRealm:(NSString *)newRealm { if(![realm isEqual:newRealm]) { [realm release]; realm = [newRealm copy]; } } - (void)setDigestURI:(NSString *)newDigestURI { if(![digestURI isEqual:newDigestURI]) { [digestURI release]; digestURI = [newDigestURI copy]; } } - (void)setUsername:(NSString *)newUsername password:(NSString *)newPassword { if(![username isEqual:newUsername]) { [username release]; username = [newUsername copy]; } if(![password isEqual:newPassword]) { [password release]; password = [newPassword copy]; } } - (NSString *)response { NSString *HA1str = [NSString stringWithFormat:@"%@:%@:%@", username, realm, password]; NSString *HA2str = [NSString stringWithFormat:@"AUTHENTICATE:%@", digestURI]; NSData *HA1dataA = [[HA1str dataUsingEncoding:NSUTF8StringEncoding] md5Digest]; NSData *HA1dataB = [[NSString stringWithFormat:@":%@:%@", nonce, cnonce] dataUsingEncoding:NSUTF8StringEncoding]; NSMutableData *HA1data = [NSMutableData dataWithCapacity:([HA1dataA length] + [HA1dataB length])]; [HA1data appendData:HA1dataA]; [HA1data appendData:HA1dataB]; NSString *HA1 = [[HA1data md5Digest] hexStringValue]; NSString *HA2 = [[[HA2str dataUsingEncoding:NSUTF8StringEncoding] md5Digest] hexStringValue]; NSString *responseStr = [NSString stringWithFormat:@"%@:%@:00000001:%@:auth:%@", HA1, nonce, cnonce, HA2]; NSString *response = [[[responseStr dataUsingEncoding:NSUTF8StringEncoding] md5Digest] hexStringValue]; return response; } - (NSString *)base64EncodedFullResponse { NSMutableString *buffer = [NSMutableString stringWithCapacity:100]; [buffer appendFormat:@"username=\"%@\",", username]; [buffer appendFormat:@"realm=\"%@\",", realm]; [buffer appendFormat:@"nonce=\"%@\",", nonce]; [buffer appendFormat:@"cnonce=\"%@\",", cnonce]; [buffer appendFormat:@"nc=00000001,"]; [buffer appendFormat:@"qop=auth,"]; [buffer appendFormat:@"digest-uri=\"%@\",", digestURI]; [buffer appendFormat:@"response=%@,", [self response]]; [buffer appendFormat:@"charset=utf-8"]; XMPPLogSend(@"decoded response: %@", buffer); NSData *utf8data = [buffer dataUsingEncoding:NSUTF8StringEncoding]; return [utf8data base64Encoded]; } @end
04081337-xmpp
Core/XMPPStream.m
Objective-C
bsd
117,106
// // The following is for XMPPStream, // and any classes that extend XMPPStream such as XMPPFacebookStream. // // Define the various timeouts (in seconds) for retreiving various parts of the XML stream #define TIMEOUT_XMPP_WRITE -1 #define TIMEOUT_XMPP_READ_START 10 #define TIMEOUT_XMPP_READ_STREAM -1 // Define the various tags we'll use to differentiate what it is we're currently reading or writing #define TAG_XMPP_READ_START 100 #define TAG_XMPP_READ_STREAM 101 #define TAG_XMPP_WRITE_START 200 #define TAG_XMPP_WRITE_STREAM 201 #define TAG_XMPP_WRITE_RECEIPT 202 // Define the various states we'll use to track our progress enum { STATE_XMPP_DISCONNECTED, STATE_XMPP_RESOLVING_SRV, STATE_XMPP_CONNECTING, STATE_XMPP_OPENING, STATE_XMPP_NEGOTIATING, STATE_XMPP_STARTTLS_1, STATE_XMPP_STARTTLS_2, STATE_XMPP_POST_NEGOTIATION, STATE_XMPP_REGISTERING, STATE_XMPP_AUTH_1, STATE_XMPP_AUTH_2, STATE_XMPP_AUTH_3, STATE_XMPP_BINDING, STATE_XMPP_START_SESSION, STATE_XMPP_CONNECTED, }; // // It is recommended that storage classes cache a stream's myJID. // This prevents them from constantly querying the property from the xmppStream instance, // as doing so goes through xmppStream's dispatch queue. // Caching the stream's myJID frees the dispatch queue to handle xmpp processing tasks. // // The object of the notification will be the XMPPStream instance. // // Note: We're not using the typical MulticastDelegate paradigm for this task as // storage classes are not typically added as a delegate of the xmppStream. // extern NSString *const XMPPStreamDidChangeMyJIDNotification;
04081337-xmpp
Core/XMPPInternal.h
C
bsd
1,654
#import <Foundation/Foundation.h> #import "GCDMulticastDelegate.h" @class XMPPStream; /** * XMPPModule is the base class that all extensions/modules inherit. * They automatically get: * * - A dispatch queue. * - A multicast delegate that automatically invokes added delegates. * * The module also automatically registers/unregisters itself with the * xmpp stream during the activate/deactive methods. **/ @interface XMPPModule : NSObject { XMPPStream *xmppStream; dispatch_queue_t moduleQueue; id multicastDelegate; } @property (readonly) dispatch_queue_t moduleQueue; @property (readonly) XMPPStream *xmppStream; - (id)init; - (id)initWithDispatchQueue:(dispatch_queue_t)queue; - (BOOL)activate:(XMPPStream *)xmppStream; - (void)deactivate; - (void)addDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue; - (void)removeDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue; - (void)removeDelegate:(id)delegate; - (NSString *)moduleName; @end
04081337-xmpp
Core/XMPPModule.h
Objective-C
bsd
996
#import <Foundation/Foundation.h> #if TARGET_OS_IPHONE #import "DDXML.h" #endif @class XMPPJID; /** * The XMPPElement provides the base class for XMPPIQ, XMPPMessage & XMPPPresence. * * This class extends NSXMLElement. * The NSXML classes (NSXMLElement & NSXMLNode) provide a full-featured library for working with XML elements. * * On the iPhone, the KissXML library provides a drop-in replacement for Apple's NSXML classes. **/ @interface XMPPElement : NSXMLElement <NSCoding> - (NSString *)elementID; - (XMPPJID *)to; - (XMPPJID *)from; - (NSString *)toStr; - (NSString *)fromStr; @end
04081337-xmpp
Core/XMPPElement.h
Objective-C
bsd
607
#import <Foundation/Foundation.h> #import "XMPPElement.h" /** * The XMPPPresence class represents a <presence> element. * It extends XMPPElement, which in turn extends NSXMLElement. * All <presence> elements that go in and out of the * xmpp stream will automatically be converted to XMPPPresence objects. * * This class exists to provide developers an easy way to add functionality to presence processing. * Simply add your own category to XMPPPresence to extend it with your own custom methods. **/ @interface XMPPPresence : XMPPElement // Converts an NSXMLElement to an XMPPPresence element in place (no memory allocations or copying) + (XMPPPresence *)presenceFromElement:(NSXMLElement *)element; + (XMPPPresence *)presence; + (XMPPPresence *)presenceWithType:(NSString *)type; + (XMPPPresence *)presenceWithType:(NSString *)type to:(XMPPJID *)to; - (id)init; - (id)initWithType:(NSString *)type; - (id)initWithType:(NSString *)type to:(XMPPJID *)to; - (NSString *)type; - (NSString *)show; - (NSString *)status; - (int)priority; - (int)intShow; - (BOOL)isErrorPresence; @end
04081337-xmpp
Core/XMPPPresence.h
Objective-C
bsd
1,098
#import "XMPPJID.h" #import "LibIDN.h" @implementation XMPPJID + (BOOL)validateDomain:(NSString *)domain { // Domain is the only required part of a JID if ((domain == nil) || ([domain length] == 0)) return NO; // If there's an @ symbol in the domain it probably means user put @ in their username NSRange invalidAtRange = [domain rangeOfString:@"@"]; if (invalidAtRange.location != NSNotFound) return NO; return YES; } + (BOOL)validateResource:(NSString *)resource { // Can't use an empty string resource name if ((resource != nil) && ([resource length] == 0)) return NO; return YES; } + (BOOL)validateUser:(NSString *)user domain:(NSString *)domain resource:(NSString *)resource { if (![self validateDomain:domain]) return NO; if (![self validateResource:resource]) return NO; return YES; } + (BOOL)parse:(NSString *)jidStr outUser:(NSString **)user outDomain:(NSString **)domain outResource:(NSString **)resource { if(user) *user = nil; if(domain) *domain = nil; if(resource) *resource = nil; if(jidStr == nil) return NO; NSString *rawUser = nil; NSString *rawDomain = nil; NSString *rawResource = nil; NSRange atRange = [jidStr rangeOfString:@"@"]; if(atRange.location != NSNotFound) { rawUser = [jidStr substringToIndex:atRange.location]; NSString *minusUser = [jidStr substringFromIndex:atRange.location+1]; NSRange slashRange = [minusUser rangeOfString:@"/"]; if(slashRange.location != NSNotFound) { rawDomain = [minusUser substringToIndex:slashRange.location]; rawResource = [minusUser substringFromIndex:slashRange.location+1]; } else { rawDomain = minusUser; } } else { NSRange slashRange = [jidStr rangeOfString:@"/"]; if(slashRange.location != NSNotFound) { rawDomain = [jidStr substringToIndex:slashRange.location]; rawResource = [jidStr substringFromIndex:slashRange.location+1]; } else { rawDomain = jidStr; } } NSString *prepUser = [LibIDN prepNode:rawUser]; NSString *prepDomain = [LibIDN prepDomain:rawDomain]; NSString *prepResource = [LibIDN prepResource:rawResource]; if([XMPPJID validateUser:prepUser domain:prepDomain resource:prepResource]) { if(user) *user = prepUser; if(domain) *domain = prepDomain; if(resource) *resource = prepResource; return YES; } return NO; } + (XMPPJID *)jidWithString:(NSString *)jidStr { NSString *user; NSString *domain; NSString *resource; if([XMPPJID parse:jidStr outUser:&user outDomain:&domain outResource:&resource]) { XMPPJID *jid = [[XMPPJID alloc] init]; jid->user = [user copy]; jid->domain = [domain copy]; jid->resource = [resource copy]; return [jid autorelease]; } return nil; } + (XMPPJID *)jidWithString:(NSString *)jidStr resource:(NSString *)resource { if(![self validateResource:resource]) return nil; NSString *user; NSString *domain; if([XMPPJID parse:jidStr outUser:&user outDomain:&domain outResource:nil]) { XMPPJID *jid = [[XMPPJID alloc] init]; jid->user = [user copy]; jid->domain = [domain copy]; jid->resource = [resource copy]; return [jid autorelease]; } return nil; } + (XMPPJID *)jidWithUser:(NSString *)user domain:(NSString *)domain resource:(NSString *)resource { NSString *prepUser = [LibIDN prepNode:user]; NSString *prepDomain = [LibIDN prepDomain:domain]; NSString *prepResource = [LibIDN prepResource:resource]; if([XMPPJID validateUser:prepUser domain:prepDomain resource:prepResource]) { XMPPJID *jid = [[XMPPJID alloc] init]; jid->user = [prepUser copy]; jid->domain = [prepDomain copy]; jid->resource = [prepResource copy]; return [jid autorelease]; } return nil; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Encoding, Decoding: //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #if ! TARGET_OS_IPHONE - (id)replacementObjectForPortCoder:(NSPortCoder *)encoder { if([encoder isBycopy]) return self; else return [super replacementObjectForPortCoder:encoder]; // return [NSDistantObject proxyWithLocal:self connection:[encoder connection]]; } #endif - (id)initWithCoder:(NSCoder *)coder { if((self = [super init])) { if([coder allowsKeyedCoding]) { user = [[coder decodeObjectForKey:@"user"] copy]; domain = [[coder decodeObjectForKey:@"domain"] copy]; resource = [[coder decodeObjectForKey:@"resource"] copy]; } else { user = [[coder decodeObject] copy]; domain = [[coder decodeObject] copy]; resource = [[coder decodeObject] copy]; } } return self; } - (void)encodeWithCoder:(NSCoder *)coder { if([coder allowsKeyedCoding]) { [coder encodeObject:user forKey:@"user"]; [coder encodeObject:domain forKey:@"domain"]; [coder encodeObject:resource forKey:@"resource"]; } else { [coder encodeObject:user]; [coder encodeObject:domain]; [coder encodeObject:resource]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Copying: //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (id)copyWithZone:(NSZone *)zone { // This class is immutable return [self retain]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Normal Methods: //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Why didn't we just synthesize these properties? // // Since these variables are readonly within the class, // we want the synthesized methods to work like a nonatomic property. // In order to do this, we have to mark the properties as nonatomic in the header. // However we don't like marking the property as nonatomic in the header because // then people might think it's not thread-safe when in fact it is. - (NSString *)user { return user; // Why didn't we just synthesize this? See comment above. } - (NSString *)domain { return domain; // Why didn't we just synthesize this? See comment above. } - (NSString *)resource { return resource; // Why didn't we just synthesize this? See comment above. } - (XMPPJID *)bareJID { if(resource == nil) { return [[self retain] autorelease]; } else { return [XMPPJID jidWithUser:user domain:domain resource:nil]; } } - (XMPPJID *)domainJID { if(user == nil && resource == nil) { return [[self retain] autorelease]; } else { return [XMPPJID jidWithUser:nil domain:domain resource:nil]; } } - (NSString *)bare { if(user) return [NSString stringWithFormat:@"%@@%@", user, domain]; else return domain; } - (NSString *)full { if(user) { if(resource) return [NSString stringWithFormat:@"%@@%@/%@", user, domain, resource]; else return [NSString stringWithFormat:@"%@@%@", user, domain]; } else { if(resource) return [NSString stringWithFormat:@"%@/%@", domain, resource]; else return domain; } } - (BOOL)isBare { // From RFC 6120 Terminology: // // The term "bare JID" refers to an XMPP address of the form <localpart@domainpart> (for an account at a server) // or of the form <domainpart> (for a server). return (resource == nil); } - (BOOL)isBareWithUser { return (user != nil && resource == nil); } - (BOOL)isFull { // From RFC 6120 Terminology: // // The term "full JID" refers to an XMPP address of the form // <localpart@domainpart/resourcepart> (for a particular authorized client or device associated with an account) // or of the form <domainpart/resourcepart> (for a particular resource or script associated with a server). return (resource != nil); } - (BOOL)isFullWithUser { return (user != nil && resource != nil); } - (BOOL)isServer { return (user == nil); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark NSObject Methods: //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4 - (unsigned)hash { return [[self full] hash]; } #else - (NSUInteger)hash { return [[self full] hash]; } #endif - (BOOL)isEqual:(id)anObject { if ([anObject isMemberOfClass:[self class]]) { return [self isEqualToJID:(XMPPJID *)anObject]; } return NO; } - (BOOL)isEqualToJID:(XMPPJID *)aJID { if (aJID == nil) return NO; if (user) { if (![user isEqualToString:aJID->user]) return NO; } else { if (aJID->user) return NO; } if (domain) { if (![domain isEqualToString:aJID->domain]) return NO; } else { if (aJID->domain) return NO; } if (resource) { if (![resource isEqualToString:aJID->resource]) return NO; } else { if (aJID->resource) return NO; } return YES; } - (NSString *)description { return [self full]; } - (void)dealloc { [user release]; [domain release]; [resource release]; [super dealloc]; } @end
04081337-xmpp
Core/XMPPJID.m
Objective-C
bsd
9,165
#import "XMPPPresence.h" #import "NSXMLElement+XMPP.h" #import <objc/runtime.h> @implementation XMPPPresence + (void)initialize { // We use the object_setClass method below to dynamically change the class from a standard NSXMLElement. // The size of the two classes is expected to be the same. // // If a developer adds instance methods to this class, bad things happen at runtime that are very hard to debug. // This check is here to aid future developers who may make this mistake. // // For Fearless And Experienced Objective-C Developers: // It may be possible to support adding instance variables to this class if you seriously need it. // To do so, try realloc'ing self after altering the class, and then initialize your variables. size_t superSize = class_getInstanceSize([NSXMLElement class]); size_t ourSize = class_getInstanceSize([XMPPPresence class]); if (superSize != ourSize) { NSLog(@"Adding instance variables to XMPPPresence is not currently supported!"); exit(15); } } + (XMPPPresence *)presenceFromElement:(NSXMLElement *)element { object_setClass(element, [XMPPPresence class]); return (XMPPPresence *)element; } + (XMPPPresence *)presence { return [[[XMPPPresence alloc] init] autorelease]; } + (XMPPPresence *)presenceWithType:(NSString *)type { return [[[XMPPPresence alloc] initWithType:type to:nil] autorelease]; } + (XMPPPresence *)presenceWithType:(NSString *)type to:(XMPPJID *)to { return [[[XMPPPresence alloc] initWithType:type to:to] autorelease]; } - (id)init { self = [super initWithName:@"presence"]; return self; } - (id)initWithType:(NSString *)type { return [self initWithType:type to:nil]; } - (id)initWithType:(NSString *)type to:(XMPPJID *)to { if ((self = [super initWithName:@"presence"])) { if (type) [self addAttributeWithName:@"type" stringValue:type]; if (to) [self addAttributeWithName:@"to" stringValue:[to description]]; } return self; } - (NSString *)type { NSString *type = [self attributeStringValueForName:@"type"]; if(type) return [type lowercaseString]; else return @"available"; } - (NSString *)show { return [[self elementForName:@"show"] stringValue]; } - (NSString *)status { return [[self elementForName:@"status"] stringValue]; } - (int)priority { return [[[self elementForName:@"priority"] stringValue] intValue]; } - (int)intShow { NSString *show = [self show]; if([show isEqualToString:@"dnd"]) return 0; if([show isEqualToString:@"xa"]) return 1; if([show isEqualToString:@"away"]) return 2; if([show isEqualToString:@"chat"]) return 4; return 3; } - (BOOL)isErrorPresence { return [[self type] isEqualToString:@"error"]; } @end
04081337-xmpp
Core/XMPPPresence.m
Objective-C
bsd
2,696
#import <Foundation/Foundation.h> #import <libxml2/libxml/parser.h> #if TARGET_OS_IPHONE #import "DDXML.h" #endif @interface XMPPParser : NSObject { id delegate; BOOL hasReportedRoot; unsigned depth; xmlParserCtxt *parserCtxt; } - (id)initWithDelegate:(id)delegate; - (id)delegate; - (void)setDelegate:(id)delegate; /** * Synchronously parses the given data. * This means the delegate methods will get called before this method returns. **/ - (void)parseData:(NSData *)data; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @protocol XMPPParserDelegate @optional - (void)xmppParser:(XMPPParser *)sender didReadRoot:(NSXMLElement *)root; - (void)xmppParser:(XMPPParser *)sender didReadElement:(NSXMLElement *)element; - (void)xmppParserDidEnd:(XMPPParser *)sender; - (void)xmppParser:(XMPPParser *)sender didFail:(NSError *)error; @end
04081337-xmpp
Core/XMPPParser.h
Objective-C
bsd
1,074
#import <Foundation/Foundation.h> #import "XMPPElement.h" /** * The XMPPMessage class represents a <message> element. * It extends XMPPElement, which in turn extends NSXMLElement. * All <message> elements that go in and out of the * xmpp stream will automatically be converted to XMPPMessage objects. * * This class exists to provide developers an easy way to add functionality to message processing. * Simply add your own category to XMPPMessage to extend it with your own custom methods. **/ @interface XMPPMessage : XMPPElement // Converts an NSXMLElement to an XMPPMessage element in place (no memory allocations or copying) + (XMPPMessage *)messageFromElement:(NSXMLElement *)element; + (XMPPMessage *)message; - (id)init; - (BOOL)isChatMessage; - (BOOL)isChatMessageWithBody; - (BOOL)isErrorMessage; - (BOOL)isMessageWithBody; - (BOOL)hasReceiptRequest; - (BOOL)hasReceiptResponse; - (NSString *)extractReceiptResponseID; - (XMPPMessage *)generateReceiptResponse; - (NSError *)errorMessage; @end
04081337-xmpp
Core/XMPPMessage.h
Objective-C
bsd
1,019
#import "XMPPModule.h" #import "XMPPStream.h" #import "XMPPLogging.h" // Log levels: off, error, warn, info, verbose #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #endif @implementation XMPPModule /** * Standard init method. **/ - (id)init { return [self initWithDispatchQueue:NULL]; } /** * Designated initializer. **/ - (id)initWithDispatchQueue:(dispatch_queue_t)queue { if ((self = [super init])) { if (queue) { moduleQueue = queue; dispatch_retain(moduleQueue); } else { const char *moduleQueueName = [[self moduleName] UTF8String]; moduleQueue = dispatch_queue_create(moduleQueueName, NULL); } multicastDelegate = [[GCDMulticastDelegate alloc] init]; } return self; } - (void)dealloc { if (xmppStream) { // It is dangerous to rely on the dealloc method to deactivate a module. // // Why? // Because when a module is activated, it is added as a delegate to the xmpp stream. // In addition to this, the module may be added as a delegate to various other xmpp components. // As per usual, these delegate references do NOT retain this module. // This means that modules may get invoked after they are deallocated. // // Consider the following example: // // 1. Thread A: Module is created (alloc/init) (retainCount = 1) // 2. Thread A: Module is activated (retainCount = 1) // 3. Thread A: Module is released, and dealloc is called. // First [MyCustomModule dealloc] is invoked. // Then [XMPPModule dealloc] is invoked. // Only at this point is [XMPPModule deactivate] run. // Since the deactivate method is synchronous, // it blocks until the module is removed as a delegate from the stream and all other modules. // 4. Thread B: Invokes a delegate method on our module ([XMPPModule deactivate] is waiting on thread B). // 5. Thread A: The [XMPPModule deactivate] method returns, but the damage is done. // Thread B has asynchronously dispatched a delegate method set to run on our module. // 6. Thread A: The dealloc method completes, and our module is now deallocated. // 7. Thread C: The delegate method attempts to run on our module, which is deallocated, // the application crashes, the computer blows up, and a meteor hits your favorite restaurant. XMPPLogWarn(@"%@: Deallocating activated module. You should deactivate modules before their final release.", NSStringFromClass([self class])); [self deactivate]; } [multicastDelegate release]; dispatch_release(moduleQueue); [super dealloc]; } /** * The activate method is the point at which the module gets plugged into the xmpp stream. * Subclasses may override this method to perform any custom actions, * but must invoke [super activate:aXmppStream] at some point within their implementation. **/ - (BOOL)activate:(XMPPStream *)aXmppStream { __block BOOL result = YES; dispatch_block_t block = ^{ if (xmppStream != nil) { result = NO; } else { xmppStream = [aXmppStream retain]; [xmppStream addDelegate:self delegateQueue:moduleQueue]; [xmppStream registerModule:self]; } }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_sync(moduleQueue, block); return result; } /** * The deactivate method unplugs a module from the xmpp stream. * When this method returns, no further delegate methods on this module will be dispatched. * However, there may be delegate methods that have already been dispatched. * If this is the case, the module will be properly retained until the delegate methods have completed. * If your custom module requires that delegate methods are not run after the deactivate method has been run, * then simply check the xmppStream variable in your delegate methods. **/ - (void)deactivate { dispatch_block_t block = ^{ if (xmppStream) { [xmppStream removeDelegate:self delegateQueue:moduleQueue]; [xmppStream unregisterModule:self]; [xmppStream release]; xmppStream = nil; } }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_sync(moduleQueue, block); } - (dispatch_queue_t)moduleQueue { if (dispatch_get_current_queue() == moduleQueue) { return moduleQueue; } else { __block dispatch_queue_t result; dispatch_sync(moduleQueue, ^{ result = moduleQueue; }); return result; } } - (XMPPStream *)xmppStream { if (dispatch_get_current_queue() == moduleQueue) { return xmppStream; } else { __block XMPPStream *result; dispatch_sync(moduleQueue, ^{ result = [xmppStream retain]; }); return [result autorelease]; } } - (void)addDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue { // Asynchronous operation (if outside xmppQueue) dispatch_block_t block = ^{ [multicastDelegate addDelegate:delegate delegateQueue:delegateQueue]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } - (void)removeDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue { // Synchronous operation // // Delegate removal MUST always be synchronous. dispatch_block_t block = ^{ [multicastDelegate removeDelegate:delegate delegateQueue:delegateQueue]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_sync(moduleQueue, block); } - (void)removeDelegate:(id)delegate { // Synchronous operation // // Delegate remove MUST always be synchronous. dispatch_block_t block = ^{ [multicastDelegate removeDelegate:delegate]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_sync(moduleQueue, block); } - (NSString *)moduleName { // Override me to provide a proper module name. // The name may be used as the name of the dispatch_queue which could aid in debugging. return @"XMPPModule"; } @end
04081337-xmpp
Core/XMPPModule.m
Objective-C
bsd
6,019
#import "XMPPMessage.h" #import "XMPPJID.h" #import "NSXMLElement+XMPP.h" #import <objc/runtime.h> @implementation XMPPMessage + (void)initialize { // We use the object_setClass method below to dynamically change the class from a standard NSXMLElement. // The size of the two classes is expected to be the same. // // If a developer adds instance methods to this class, bad things happen at runtime that are very hard to debug. // This check is here to aid future developers who may make this mistake. // // For Fearless And Experienced Objective-C Developers: // It may be possible to support adding instance variables to this class if you seriously need it. // To do so, try realloc'ing self after altering the class, and then initialize your variables. size_t superSize = class_getInstanceSize([NSXMLElement class]); size_t ourSize = class_getInstanceSize([XMPPMessage class]); if (superSize != ourSize) { NSLog(@"Adding instance variables to XMPPMessage is not currently supported!"); exit(15); } } + (XMPPMessage *)messageFromElement:(NSXMLElement *)element { object_setClass(element, [XMPPMessage class]); return (XMPPMessage *)element; } + (XMPPMessage *)message { return [[[XMPPMessage alloc] init] autorelease]; } - (id)init { self = [super initWithName:@"message"]; return self; } - (BOOL)isChatMessage { return [[[self attributeForName:@"type"] stringValue] isEqualToString:@"chat"]; } - (BOOL)isChatMessageWithBody { if([self isChatMessage]) { return [self isMessageWithBody]; } return NO; } - (BOOL)isErrorMessage { return [[[self attributeForName:@"type"] stringValue] isEqualToString:@"error"]; } - (NSError *)errorMessage { if (![self isErrorMessage]) { return nil; } NSXMLElement *error = [self elementForName:@"error"]; return [NSError errorWithDomain:@"urn:ietf:params:xml:ns:xmpp-stanzas" code:[error attributeIntValueForName:@"code"] userInfo:[NSDictionary dictionaryWithObject:[error compactXMLString] forKey:NSLocalizedDescriptionKey]]; } - (BOOL)isMessageWithBody { NSString *body = [[self elementForName:@"body"] stringValue]; return ((body != nil) && ([body length] > 0)); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XEP-0184: Message Receipts //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (BOOL)hasReceiptRequest { NSXMLElement *receiptRequest = [self elementForName:@"request" xmlns:@"urn:xmpp:receipts"]; return (receiptRequest != nil); } - (BOOL)hasReceiptResponse { NSXMLElement *receiptResponse = [self elementForName:@"received" xmlns:@"urn:xmpp:receipts"]; return (receiptResponse != nil); } - (NSString *)extractReceiptResponseID { NSXMLElement *receiptResponse = [self elementForName:@"received" xmlns:@"urn:xmpp:receipts"]; return [receiptResponse attributeStringValueForName:@"id"]; } - (XMPPMessage *)generateReceiptResponse { // Example: // // <message to="juliet"> // <received xmlns="urn:xmpp:receipts" id="ABC-123"/> // </message> NSXMLElement *received = [NSXMLElement elementWithName:@"received" xmlns:@"urn:xmpp:receipts"]; NSXMLElement *message = [NSXMLElement elementWithName:@"message"]; NSString *to = [self fromStr]; if(to) { [message addAttributeWithName:@"to" stringValue:to]; } NSString *msgid = [self elementID]; if(msgid) { [received addAttributeWithName:@"id" stringValue:msgid]; } [message addChild:received]; return [[self class] messageFromElement:message]; } @end
04081337-xmpp
Core/XMPPMessage.m
Objective-C
bsd
3,709
#import "XMPPJID.h" #import "XMPPStream.h" #import "XMPPElement.h" #import "XMPPIQ.h" #import "XMPPMessage.h" #import "XMPPPresence.h" #import "XMPPModule.h" #import "NSXMLElement+XMPP.h"
04081337-xmpp
Core/XMPP.h
Objective-C
bsd
189
#import <Foundation/Foundation.h> @interface XMPPJID : NSObject <NSCoding, NSCopying> { NSString *user; NSString *domain; NSString *resource; } + (XMPPJID *)jidWithString:(NSString *)jidStr; + (XMPPJID *)jidWithString:(NSString *)jidStr resource:(NSString *)resource; + (XMPPJID *)jidWithUser:(NSString *)user domain:(NSString *)domain resource:(NSString *)resource; @property (readonly) NSString *user; @property (readonly) NSString *domain; @property (readonly) NSString *resource; - (XMPPJID *)bareJID; - (XMPPJID *)domainJID; - (NSString *)bare; - (NSString *)full; - (BOOL)isBare; - (BOOL)isBareWithUser; - (BOOL)isFull; - (BOOL)isFullWithUser; - (BOOL)isServer; /** * When you know both objects are JIDs, this method is a faster way to check equality than isEqual:. **/ - (BOOL)isEqualToJID:(XMPPJID *)aJID; @end
04081337-xmpp
Core/XMPPJID.h
Objective-C
bsd
835
#import "XMPPElement.h" #import "XMPPJID.h" #import "NSXMLElement+XMPP.h" @implementation XMPPElement //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Encoding, Decoding //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #if ! TARGET_OS_IPHONE - (id)replacementObjectForPortCoder:(NSPortCoder *)encoder { if([encoder isBycopy]) return self; else return [super replacementObjectForPortCoder:encoder]; // return [NSDistantObject proxyWithLocal:self connection:[encoder connection]]; } #endif - (id)initWithCoder:(NSCoder *)coder { NSString *xmlString; if([coder allowsKeyedCoding]) { xmlString = [coder decodeObjectForKey:@"xmlString"]; } else { xmlString = [coder decodeObject]; } return [super initWithXMLString:xmlString error:nil]; } - (void)encodeWithCoder:(NSCoder *)coder { NSString *xmlString = [self compactXMLString]; if([coder allowsKeyedCoding]) { [coder encodeObject:xmlString forKey:@"xmlString"]; } else { [coder encodeObject:xmlString]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Common Jabber Methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSString *)elementID { return [[self attributeForName:@"id"] stringValue]; } - (NSString *)toStr { return [[self attributeForName:@"to"] stringValue]; } - (NSString *)fromStr { return [[self attributeForName:@"from"] stringValue]; } - (XMPPJID *)to { return [XMPPJID jidWithString:[self toStr]]; } - (XMPPJID *)from { return [XMPPJID jidWithString:[self fromStr]]; } @end
04081337-xmpp
Core/XMPPElement.m
Objective-C
bsd
1,814
#import <Foundation/Foundation.h> #import "GCDAsyncSocket.h" #import "GCDMulticastDelegate.h" #if TARGET_OS_IPHONE #import "DDXML.h" #endif @class XMPPSRVResolver; @class DDList; @class XMPPParser; @class XMPPJID; @class XMPPIQ; @class XMPPMessage; @class XMPPPresence; @class XMPPModule; @class XMPPElementReceipt; @protocol XMPPStreamDelegate; #if TARGET_OS_IPHONE #define MIN_KEEPALIVE_INTERVAL 20.0 // 20 Seconds #define DEFAULT_KEEPALIVE_INTERVAL 120.0 // 2 Minutes #else #define MIN_KEEPALIVE_INTERVAL 10.0 // 10 Seconds #define DEFAULT_KEEPALIVE_INTERVAL 300.0 // 5 Minutes #endif extern NSString *const XMPPStreamErrorDomain; enum XMPPStreamErrorCode { XMPPStreamInvalidType, // Attempting to access P2P methods in a non-P2P stream, or vice-versa XMPPStreamInvalidState, // Invalid state for requested action, such as connect when already connected XMPPStreamInvalidProperty, // Missing a required property, such as hostName or myJID XMPPStreamInvalidParameter, // Invalid parameter, such as a nil JID XMPPStreamUnsupportedAction, // The server doesn't support the requested action }; typedef enum XMPPStreamErrorCode XMPPStreamErrorCode; @interface XMPPStream : NSObject <GCDAsyncSocketDelegate> { dispatch_queue_t xmppQueue; dispatch_queue_t parserQueue; GCDMulticastDelegate <XMPPStreamDelegate> *multicastDelegate; int state; GCDAsyncSocket *asyncSocket; NSMutableData *socketBuffer; UInt64 numberOfBytesSent; UInt64 numberOfBytesReceived; XMPPParser *parser; NSError *parserError; Byte flags; Byte config; NSString *hostName; UInt16 hostPort; NSString *tempPassword; XMPPJID *myJID; XMPPJID *remoteJID; XMPPPresence *myPresence; NSXMLElement *rootElement; NSTimeInterval keepAliveInterval; dispatch_source_t keepAliveTimer; dispatch_time_t lastSendReceiveTime; DDList *registeredModules; NSMutableDictionary *autoDelegateDict; XMPPSRVResolver *srvResolver; NSArray *srvResults; NSUInteger srvResultsIndex; NSMutableArray *receipts; NSThread *xmppUtilityThread; NSRunLoop *xmppUtilityRunLoop; id userTag; } /** * Standard XMPP initialization. * The stream is a standard client to server connection. * * P2P streams using XEP-0174 are also supported. * See the P2P section below. **/ - (id)init; /** * Peer to Peer XMPP initialization. * The stream is a direct client to client connection as outlined in XEP-0174. **/ - (id)initP2PFrom:(XMPPJID *)myJID; /** * XMPPStream uses a multicast delegate. * This allows one to add multiple delegates to a single XMPPStream instance, * which makes it easier to separate various components and extensions. * * For example, if you were implementing two different custom extensions on top of XMPP, * you could put them in separate classes, and simply add each as a delegate. **/ - (void)addDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue; - (void)removeDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue; - (void)removeDelegate:(id)delegate; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Properties //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * The server's hostname that should be used to make the TCP connection. * This may be a domain name (e.g. "deusty.com") or an IP address (e.g. "70.85.193.226"). * * Note that this may be different from the virtual xmpp hostname. * Just as HTTP servers can support mulitple virtual hosts from a single server, so too can xmpp servers. * A prime example is google via google apps. * * For example, say you own the domain "mydomain.com". * If you go to mydomain.com in a web browser, * you are directed to your apache server running on your webserver somewhere in the cloud. * But you use google apps for your email and xmpp needs. * So if somebody sends you an email, it actually goes to google's servers, where you later access it from. * Similarly, you connect to google's servers to sign into xmpp. * * In the example above, your hostname is "talk.google.com" and your JID is "me@mydomain.com". * * This hostName property is optional. * If you do not set the hostName, then the framework will follow the xmpp specification using jid's domain. * That is, it first do an SRV lookup (as specified in the xmpp RFC). * If that fails, it will fall back to simply attempting to connect to the jid's domain. **/ @property (readwrite, copy) NSString *hostName; /** * The port the xmpp server is running on. * If you do not explicitly set the port, the default port will be used. * If you set the port to zero, the default port will be used. * * The default port is 5222. **/ @property (readwrite, assign) UInt16 hostPort; /** * The JID of the user. * * This value is required, and is used in many parts of the underlying implementation. * When connecting, the domain of the JID is used to properly specify the correct xmpp virtual host. * It is used during registration to supply the username of the user to create an account for. * It is used during authentication to supply the username of the user to authenticate with. * And the resource may be used post-authentication during the required xmpp resource binding step. * * A proper JID is of the form user@domain/resource. * For example: robbiehanson@deusty.com/work * * The resource is optional, in the sense that if one is not supplied, * one will be automatically generated for you (either by us or by the server). * * Please note: * Resource collisions are handled in different ways depending on server configuration. * * For example: * You are signed in with user1@domain.com/home on your desktop. * Then you attempt to sign in with user1@domain.com/home on your laptop. * * The server could possibly: * - Reject the resource request for the laptop. * - Accept the resource request for the laptop, and immediately disconnect the desktop. * - Automatically assign the laptop another resource without a conflict. * * For this reason, you may wish to check the myJID variable after the stream has been connected, * just in case the resource was changed by the server. **/ @property (readwrite, copy) XMPPJID *myJID; /** * Only used in P2P streams. **/ @property (readonly) XMPPJID *remoteJID; /** * Many routers will teardown a socket mapping if there is no activity on the socket. * For this reason, the xmpp stream supports sending keep-alive data. * This is simply whitespace, which is ignored by the xmpp protocol. * * Keep-alive data is only sent in the absence of any other data being sent/received. * * The default value is defined in DEFAULT_KEEPALIVE_INTERVAL. * The minimum value is defined in MIN_KEEPALIVE_INTERVAL. * * To disable keep-alive, set the interval to zero. * * The keep-alive timer (if enabled) fires every (keepAliveInterval / 4) seconds. * Upon firing it checks when data was last sent/received, * and sends keep-alive data if the elapsed time has exceeded the keepAliveInterval. * Thus the effective resolution of the keepalive timer is based on the interval. **/ @property (readwrite, assign) NSTimeInterval keepAliveInterval; /** * Represents the last sent presence element concerning the presence of myJID on the server. * In other words, it represents the presence as others see us. * * This excludes presence elements sent concerning subscriptions, MUC rooms, etc. **/ @property (readonly) XMPPPresence *myPresence; /** * Returns the total number of bytes bytes sent/received by the xmpp stream. * * By default this is the byte count since the xmpp stream object has been created. * If the stream has connected/disconnected/reconnected multiple times, * the count will be the summation of all connections. * * The functionality may optionaly be changed to count only the current socket connection. * See the resetByteCountPerConnection property. **/ @property (readonly) UInt64 numberOfBytesSent; @property (readonly) UInt64 numberOfBytesReceived; /** * Affects the funtionality of the byte counter. * * The default value is NO. * * If set to YES, the byte count will be reset just prior to a new connection (in the connect methods). **/ @property (readwrite, assign) BOOL resetByteCountPerConnection; /** * The tag property allows you to associate user defined information with the stream. * Tag values are not used internally, and should not be used by xmpp modules. **/ @property (readwrite, retain) id tag; #if TARGET_OS_IPHONE /** * If set, the kCFStreamNetworkServiceTypeVoIP flags will be set on the underlying CFRead/Write streams. * * The default value is NO. **/ @property (readwrite, assign) BOOL enableBackgroundingOnSocket; #endif //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark State //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Returns YES if the connection is closed, and thus no stream is open. * If the stream is neither disconnected, nor connected, then a connection is currently being established. **/ - (BOOL)isDisconnected; /** * Returns YES if the connection is open, and the stream has been properly established. * If the stream is neither disconnected, nor connected, then a connection is currently being established. * * If this method returns YES, then it is ready for you to start sending and receiving elements. **/ - (BOOL)isConnected; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Connect & Disconnect //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Connects to the configured hostName on the configured hostPort. * If the hostName or myJID are not set, this method will return NO and set the error parameter. **/ - (BOOL)connect:(NSError **)errPtr; /** * THIS IS DEPRECATED BY THE XMPP SPECIFICATION. * * The xmpp specification outlines the proper use of SSL/TLS by negotiating * the startTLS upgrade within the stream negotiation. * This method exists for those ancient servers that still require the connection to be secured prematurely. * * Note: Such servers generally use port 5223 for this, which you will need to set. **/ - (BOOL)oldSchoolSecureConnect:(NSError **)errPtr; /** * Starts a P2P connection to the given user and given address. * This method only works with XMPPStream objects created using the initP2P method. * * The given address is specified as a sockaddr structure wrapped in a NSData object. * For example, a NSData object returned from NSNetservice's addresses method. **/ - (BOOL)connectTo:(XMPPJID *)remoteJID withAddress:(NSData *)remoteAddr error:(NSError **)errPtr; /** * Starts a P2P connection with the given accepted socket. * This method only works with XMPPStream objects created using the initP2P method. * * The given socket should be a socket that has already been accepted. * The remoteJID will be extracted from the opening stream negotiation. **/ - (BOOL)connectP2PWithSocket:(GCDAsyncSocket *)acceptedSocket error:(NSError **)errPtr; /** * Disconnects from the remote host by closing the underlying TCP socket connection. * * The disconnect method is synchronous. * Meaning that the disconnect will happen immediately, even if there are pending elements yet to be sent. * The xmppStreamDidDisconnect:withError: method will be invoked before the disconnect method returns. * * The disconnectAfterSending method is asynchronous. * The disconnect will happen after all pending elements have been sent. * Attempting to send elements after this method is called will not result in the elements getting sent. * The disconnectAfterSending method will return immediately, * and the xmppStreamDidDisconnect:withError: delegate method will be invoked at a later time. **/ - (void)disconnect; - (void)disconnectAfterSending; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Security //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Returns YES if SSL/TLS was used to establish a connection to the server. * * Some servers may require an "upgrade to TLS" in order to start communication, * so even if the connection was not explicitly secured, an ugrade to TLS may have occured. * * See also the xmppStream:willSecureWithSettings: delegate method. **/ - (BOOL)isSecure; /** * Returns whether or not the server supports securing the connection via SSL/TLS. * * Some servers will actually require a secure connection, * in which case the stream will attempt to secure the connection during the opening process. * * If the connection has already been secured, this method may return NO. **/ - (BOOL)supportsStartTLS; /** * Attempts to secure the connection via SSL/TLS. * * This method is asynchronous. * The SSL/TLS handshake will occur in the background, and * the xmppStreamDidSecure: delegate method will be called after the TLS process has completed. * * This method returns immediately. * If the secure process was started, it will return YES. * If there was an issue while starting the security process, * this method will return NO and set the error parameter. * * The errPtr parameter is optional - you may pass nil. * * You may wish to configure the security settings via the xmppStream:willSecureWithSettings: delegate method. * * If the SSL/TLS handshake fails, the connection will be closed. * The reason for the error will be reported via the xmppStreamDidDisconnect:withError: delegate method. * The error parameter will be an NSError object, and may have an error domain of kCFStreamErrorDomainSSL. * The corresponding error code is documented in Apple's Security framework, in SecureTransport.h **/ - (BOOL)secureConnection:(NSError **)errPtr; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Registration //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * In Band Registration. * Creating a user account on the xmpp server within the xmpp protocol. * * The registerWithPassword:error: method is asynchronous. * It will return immediately, and the delegate methods are used to determine success. * See the xmppStreamDidRegister: and xmppStream:didNotRegister: methods. * * If there is something immediately wrong, such as the stream is not connected, * this method will return NO and set the error. * * The errPtr parameter is optional - you may pass nil. * * Security Note: * The password will be sent in the clear unless the stream has been secured. **/ - (BOOL)supportsInBandRegistration; - (BOOL)registerWithPassword:(NSString *)password error:(NSError **)errPtr; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Authentication //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Authentication. * * The authenticateWithPassword:error: method is asynchronous. * It will return immediately, and the delegate methods are used to determine success. * See the xmppStreamDidAuthenticate: and xmppStream:didNotAuthenticate: methods. * * If there is something immediately wrong, such as the stream is not connected, * this method will return NO and set the error. * * The errPtr parameter is optional - you may pass nil. * * The authenticateWithPassword:error: method will choose the most secure protocol to send the password. * * Security Note: * Care should be taken if sending passwords in the clear is not acceptable. * You may use the supportsXAuthentication methods below to determine * if an acceptable authentication protocol is supported. **/ - (BOOL)isAuthenticated; - (BOOL)supportsAnonymousAuthentication; - (BOOL)supportsPlainAuthentication; - (BOOL)supportsDigestMD5Authentication; - (BOOL)supportsDeprecatedPlainAuthentication; - (BOOL)supportsDeprecatedDigestAuthentication; - (BOOL)authenticateWithPassword:(NSString *)password error:(NSError **)errPtr; - (BOOL)authenticateAnonymously:(NSError **)errPtr; - (void)handleAuth1:(NSXMLElement *)response; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Server Info //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * This method will return the root element of the document. * This element contains the opening <stream:stream/> and <stream:features/> tags received from the server. * * If multiple <stream:features/> have been received during the course of stream negotiation, * the root element contains only the most recent (current) version. * * Note: The rootElement is "empty", in so much as it does not contain all the XML elements the stream has * received during it's connection. This is done for performance reasons and for the obvious benefit * of being more memory efficient. **/ - (NSXMLElement *)rootElement; /** * Returns the version attribute from the servers's <stream:stream/> element. * This should be at least 1.0 to be RFC 3920 compliant. * If no version number was set, the server is not RFC compliant, and 0 is returned. **/ - (float)serverXmppStreamVersionNumber; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Sending //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Sends the given XML element. * If the stream is not yet connected, this method does nothing. **/ - (void)sendElement:(NSXMLElement *)element; /** * Just like the sendElement: method above, * but allows you to receive a receipt that can later be used to verify the element has been sent. * * If you later want to check to see if the element has been sent: * * if ([receipt wait:0]) { * // Element has been sent * } * * If you later want to wait until the element has been sent: * * if ([receipt wait:-1]) { * // Element was sent * } else { * // Element failed to send due to disconnection * } * * It is important to understand what it means when [receipt wait:timeout] returns YES. * It does NOT mean the server has received the element. * It only means the data has been queued for sending in the underlying OS socket buffer. * * So at this point the OS will do everything in its capacity to send the data to the server, * which generally means the server will eventually receive the data. * Unless, of course, something horrible happens such as a network failure, * or a system crash, or the server crashes, etc. * * Even if you close the xmpp stream after this point, the OS will still do everything it can to send the data. **/ - (void)sendElement:(NSXMLElement *)element andGetReceipt:(XMPPElementReceipt **)receiptPtr; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Module Plug-In System //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * The XMPPModule class automatically invokes these methods when it is activated/deactivated. * * The registerModule method registers the module with the xmppStream. * If there are any other modules that have requested to be automatically added as delegates to modules of this type, * then those modules are automatically added as delegates during the asynchronous execution of this method. * * The registerModule method is asynchronous. * * The unregisterModule method unregisters the module with the xmppStream, * and automatically removes it as a delegate of any other module. * * The unregisterModule method is fully synchronous. * That is, after this method returns, the module will not be scheduled in any more delegate calls from other modules. * However, if the module was already scheduled in an existing asynchronous delegate call from another module, * the scheduled delegate invocation remains queued and will fire in the near future. * Since the delegate invocation is already queued, * the module's retainCount has been incremented, * and the module will not be deallocated until after the delegate invocation has fired. **/ - (void)registerModule:(XMPPModule *)module; - (void)unregisterModule:(XMPPModule *)module; /** * Automatically registers the given delegate with all current and future registered modules of the given class. * * That is, the given delegate will be added to the delegate list ([module addDelegate:delegate delegateQueue:dq]) to * all current and future registered modules that respond YES to [module isKindOfClass:aClass]. * * This method is used by modules to automatically integrate with other modules. * For example, a module may auto-add itself as a delegate to XMPPCapabilities * so that it can broadcast its implemented features. * * This may also be useful to clients, for example, to add a delegate to instances of something like XMPPChatRoom, * where there may be multiple instances of the module that get created during the course of an xmpp session. * * If you auto register on multiple queues, you can remove all registrations with a single * call to removeAutoDelegate::: by passing NULL as the 'dq' parameter. * * If you auto register for multiple classes, you can remove all registrations with a single * call to removeAutoDelegate::: by passing nil as the 'aClass' parameter. **/ - (void)autoAddDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue toModulesOfClass:(Class)aClass; - (void)removeAutoDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue fromModulesOfClass:(Class)aClass; /** * Allows for enumeration of the currently registered modules. * * This may be useful if the stream needs to be queried for modules of a particular type. **/ - (void)enumerateModulesWithBlock:(void (^)(XMPPModule *module, NSUInteger idx, BOOL *stop))block; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Utilities //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Generates and returns a new autoreleased UUID. * UUIDs (Universally Unique Identifiers) may also be known as GUIDs (Globally Unique Identifiers). * * The UUID is generated using the CFUUID library, which generates a unique 128 bit value. * The uuid is then translated into a string using the standard format for UUIDs: * "68753A44-4D6F-1226-9C60-0050E4C00067" * * This method is most commonly used to generate a unique id value for an xmpp element. **/ + (NSString *)generateUUID; - (NSString *)generateUUID; /** * The XMPP Framework is designed to be entirely GCD based. * However, there are various utility classes provided by Apple that are still dependent upon a thread/runloop model. * For example, monitoring a network for changes related to connectivity requires we register a runloop-based delegate. * Thus XMPPStream creates a dedicated thread/runloop for any xmpp classes that may need it. * This provides multiple benefits: * * - Development is simplified for those transitioning from previous thread/runloop versions. * - Development is simplified for those who rely on utility classes that don't yet support pure GCD, * as they don't have to setup and maintain a thread/runloop on their own. * - It prevents multiple xmpp classes from creating multiple internal threads (which would be resource costly). * * Please note: * This thread is designed to be used only if absolutely necessary. * That is, if you MUST use a class that doesn't yet support pure GCD. * If there is a GCD alternative, you should be using it instead. * For example, do NOT use NSTimer. Instead setup a GCD timer using a dispatch_source. **/ - (NSThread *)xmppUtilityThread; - (NSRunLoop *)xmppUtilityRunLoop; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @interface XMPPElementReceipt : NSObject { uint32_t atomicFlags; dispatch_semaphore_t semaphore; } /** * Element receipts allow you to check to see if the element has been sent. * The timeout parameter allows you to do any of the following: * * - Do an instantaneous check (pass timeout == 0) * - Wait until the element has been sent (pass timeout < 0) * - Wait up to a certain amount of time (pass timeout > 0) * * It is important to understand what it means when [receipt wait:timeout] returns YES. * It does NOT mean the server has received the element. * It only means the data has been queued for sending in the underlying OS socket buffer. * * So at this point the OS will do everything in its capacity to send the data to the server, * which generally means the server will eventually receive the data. * Unless, of course, something horrible happens such as a network failure, * or a system crash, or the server crashes, etc. * * Even if you close the xmpp stream after this point, the OS will still do everything it can to send the data. **/ - (BOOL)wait:(NSTimeInterval)timeout; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @protocol XMPPStreamDelegate @optional /** * This method is called before the stream begins the connection process. * * If developing an iOS app that runs in the background, this may be a good place to indicate * that this is a task that needs to continue running in the background. **/ - (void)xmppStreamWillConnect:(XMPPStream *)sender; /** * This method is called after the tcp socket has connected to the remote host. * It may be used as a hook for various things, such as updating the UI or extracting the server's IP address. * * If developing an iOS app that runs in the background, * please use XMPPStream's enableBackgroundingOnSocket property as opposed to doing it directly on the socket here. **/ - (void)xmppStream:(XMPPStream *)sender socketDidConnect:(GCDAsyncSocket *)socket; /** * This method is called after a TCP connection has been established with the server, * and the opening XML stream negotiation has started. **/ - (void)xmppStreamDidStartNegotiation:(XMPPStream *)sender; /** * This method is called immediately prior to the stream being secured via TLS/SSL. * Note that this delegate may be called even if you do not explicitly invoke the startTLS method. * Servers have the option of requiring connections to be secured during the opening process. * If this is the case, the XMPPStream will automatically attempt to properly secure the connection. * * The possible keys and values for the security settings are well documented. * Some possible keys are: * - kCFStreamSSLLevel * - kCFStreamSSLAllowsExpiredCertificates * - kCFStreamSSLAllowsExpiredRoots * - kCFStreamSSLAllowsAnyRoot * - kCFStreamSSLValidatesCertificateChain * - kCFStreamSSLPeerName * - kCFStreamSSLCertificates * * Please refer to Apple's documentation for associated values, as well as other possible keys. * * The dictionary of settings is what will be passed to the startTLS method of ther underlying AsyncSocket. * The AsyncSocket header file also contains a discussion of the security consequences of various options. * It is recommended reading if you are planning on implementing this method. * * The dictionary of settings that are initially passed will be an empty dictionary. * If you choose not to implement this method, or simply do not edit the dictionary, * then the default settings will be used. * That is, the kCFStreamSSLPeerName will be set to the configured host name, * and the default security validation checks will be performed. * * This means that authentication will fail if the name on the X509 certificate of * the server does not match the value of the hostname for the xmpp stream. * It will also fail if the certificate is self-signed, or if it is expired, etc. * * These settings are most likely the right fit for most production environments, * but may need to be tweaked for development or testing, * where the development server may be using a self-signed certificate. **/ - (void)xmppStream:(XMPPStream *)sender willSecureWithSettings:(NSMutableDictionary *)settings; /** * This method is called after the stream has been secured via SSL/TLS. * This method may be called if the server required a secure connection during the opening process, * or if the secureConnection: method was manually invoked. **/ - (void)xmppStreamDidSecure:(XMPPStream *)sender; /** * This method is called after the XML stream has been fully opened. * More precisely, this method is called after an opening <xml/> and <stream:stream/> tag have been sent and received, * and after the stream features have been received, and any required features have been fullfilled. * At this point it's safe to begin communication with the server. **/ - (void)xmppStreamDidConnect:(XMPPStream *)sender; /** * This method is called after registration of a new user has successfully finished. * If registration fails for some reason, the xmppStream:didNotRegister: method will be called instead. **/ - (void)xmppStreamDidRegister:(XMPPStream *)sender; /** * This method is called if registration fails. **/ - (void)xmppStream:(XMPPStream *)sender didNotRegister:(NSXMLElement *)error; /** * This method is called after authentication has successfully finished. * If authentication fails for some reason, the xmppStream:didNotAuthenticate: method will be called instead. **/ - (void)xmppStreamDidAuthenticate:(XMPPStream *)sender; /** * This method is called if authentication fails. **/ - (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error; /** * These methods are called after their respective XML elements are received on the stream. * * In the case of an IQ, the delegate method should return YES if it has or will respond to the given IQ. * If the IQ is of type 'get' or 'set', and no delegates respond to the IQ, * then xmpp stream will automatically send an error response. **/ - (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq; - (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message; - (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence; /** * This method is called if an XMPP error is received. * In other words, a <stream:error/>. * * However, this method may also be called for any unrecognized xml stanzas. * * Note that standard errors (<iq type='error'/> for example) are delivered normally, * via the other didReceive...: methods. **/ - (void)xmppStream:(XMPPStream *)sender didReceiveError:(NSXMLElement *)error; /** * These methods are called before their respective XML elements are sent over the stream. * These methods can be used to customize elements on the fly. * (E.g. add standard information for custom protocols.) **/ - (void)xmppStream:(XMPPStream *)sender willSendIQ:(XMPPIQ *)iq; - (void)xmppStream:(XMPPStream *)sender willSendMessage:(XMPPMessage *)message; - (void)xmppStream:(XMPPStream *)sender willSendPresence:(XMPPPresence *)presence; /** * These methods are called after their respective XML elements are sent over the stream. * These methods may be used to listen for certain events (such as an unavailable presence having been sent), * or for general logging purposes. (E.g. a central history logging mechanism). **/ - (void)xmppStream:(XMPPStream *)sender didSendIQ:(XMPPIQ *)iq; - (void)xmppStream:(XMPPStream *)sender didSendMessage:(XMPPMessage *)message; - (void)xmppStream:(XMPPStream *)sender didSendPresence:(XMPPPresence *)presence; /** * This method is called if the disconnect method is called. * It may be used to determine if a disconnection was purposeful, or due to an error. **/ - (void)xmppStreamWasToldToDisconnect:(XMPPStream *)sender; /** * This method is called after the stream is closed. * * The given error parameter will be non-nil if the error was due to something outside the general xmpp realm. * Some examples: * - The TCP socket was unexpectedly disconnected. * - The SRV resolution of the domain failed. * - Error parsing xml sent from server. **/ - (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error; /** * This method is only used in P2P mode when the connectTo:withAddress: method was used. * * It allows the delegate to read the <stream:features/> element if/when they arrive. * Recall that the XEP specifies that <stream:features/> SHOULD be sent. **/ - (void)xmppStream:(XMPPStream *)sender didReceiveP2PFeatures:(NSXMLElement *)streamFeatures; /** * This method is only used in P2P mode when the connectTo:withSocket: method was used. * * It allows the delegate to customize the <stream:features/> element, * adding any specific featues the delegate might support. **/ - (void)xmppStream:(XMPPStream *)sender willSendP2PFeatures:(NSXMLElement *)streamFeatures; /** * These methods are called as xmpp modules are registered and unregistered with the stream. * This generally corresponds to xmpp modules being initailzed and deallocated. * * The methods may be useful, for example, if a more precise auto delegation mechanism is needed * than what is available with the autoAddDelegate:toModulesOfClass: method. **/ - (void)xmppStream:(XMPPStream *)sender didRegisterModule:(id)module; - (void)xmppStream:(XMPPStream *)sender willUnregisterModule:(id)module; @end
04081337-xmpp
Core/XMPPStream.h
Objective-C
bsd
34,629
/** * In order to provide fast and flexible logging, this project uses Cocoa Lumberjack. * * The Google Code page has a wealth of documentation if you have any questions. * http://code.google.com/p/cocoalumberjack/ * * Here's what you need to know concerning how logging is setup for XMPPFramework: * * There are 4 log levels: * - Error * - Warning * - Info * - Verbose * * In addition to this, there is a Trace flag that can be enabled. * When tracing is enabled, it spits out the methods that are being called. * * Please note that tracing is separate from the log levels. * For example, one could set the log level to warning, and enable tracing. * * All logging is asynchronous, except errors. * To use logging within your own custom files, follow the steps below. * * Step 1: * Import this header in your implementation file: * * #import "XMPPLogging.h" * * Step 2: * Define your logging level in your implementation file: * * // Log levels: off, error, warn, info, verbose * static const int xmppLogLevel = XMPP_LOG_LEVEL_VERBOSE; * * If you wish to enable tracing, you could do something like this: * * // Log levels: off, error, warn, info, verbose * static const int xmppLogLevel = XMPP_LOG_LEVEL_INFO | XMPP_LOG_FLAG_TRACE; * * Step 3: * Replace your NSLog statements with XMPPLog statements according to the severity of the message. * * NSLog(@"Fatal error, no dohickey found!"); -> XMPPLogError(@"Fatal error, no dohickey found!"); * * XMPPLog has the same syntax as NSLog. * This means you can pass it multiple variables just like NSLog. * * You may optionally choose to define different log levels for debug and release builds. * You can do so like this: * * // Log levels: off, error, warn, info, verbose * #if DEBUG * static const int xmppLogLevel = XMPP_LOG_LEVEL_VERBOSE; * #else * static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; * #endif * * Xcode projects created with Xcode 4 automatically define DEBUG via the project's preprocessor macros. * If you created your project with a previous version of Xcode, you may need to add the DEBUG macro manually. **/ #import "DDLog.h" // Define logging context for every log message coming from the XMPP framework. // The logging context can be extracted from the DDLogMessage from within the logging framework. // This gives loggers, formatters, and filters the ability to optionally process them differently. #define XMPP_LOG_CONTEXT 5222 // Configure log levels. #define XMPP_LOG_FLAG_ERROR (1 << 0) // 0...00001 #define XMPP_LOG_FLAG_WARN (1 << 1) // 0...00010 #define XMPP_LOG_FLAG_INFO (1 << 2) // 0...00100 #define XMPP_LOG_FLAG_VERBOSE (1 << 3) // 0...01000 #define XMPP_LOG_LEVEL_OFF 0 // 0...00000 #define XMPP_LOG_LEVEL_ERROR (XMPP_LOG_LEVEL_OFF | XMPP_LOG_FLAG_ERROR) // 0...00001 #define XMPP_LOG_LEVEL_WARN (XMPP_LOG_LEVEL_ERROR | XMPP_LOG_FLAG_WARN) // 0...00011 #define XMPP_LOG_LEVEL_INFO (XMPP_LOG_LEVEL_WARN | XMPP_LOG_FLAG_INFO) // 0...00111 #define XMPP_LOG_LEVEL_VERBOSE (XMPP_LOG_LEVEL_INFO | XMPP_LOG_FLAG_VERBOSE) // 0...01111 // Setup fine grained logging. // The first 4 bits are being used by the standard log levels (0 - 3) // // We're going to add tracing, but NOT as a log level. // Tracing can be turned on and off independently of log level. #define XMPP_LOG_FLAG_TRACE (1 << 4) // 0...10000 // Setup the usual boolean macros. #define XMPP_LOG_ERROR (xmppLogLevel & XMPP_LOG_FLAG_ERROR) #define XMPP_LOG_WARN (xmppLogLevel & XMPP_LOG_FLAG_WARN) #define XMPP_LOG_INFO (xmppLogLevel & XMPP_LOG_FLAG_INFO) #define XMPP_LOG_VERBOSE (xmppLogLevel & XMPP_LOG_FLAG_VERBOSE) #define XMPP_LOG_TRACE (xmppLogLevel & XMPP_LOG_FLAG_TRACE) // Configure asynchronous logging. // We follow the default configuration, // but we reserve a special macro to easily disable asynchronous logging for debugging purposes. #define XMPP_LOG_ASYNC_ENABLED YES #define XMPP_LOG_ASYNC_ERROR ( NO && XMPP_LOG_ASYNC_ENABLED) #define XMPP_LOG_ASYNC_WARN (YES && XMPP_LOG_ASYNC_ENABLED) #define XMPP_LOG_ASYNC_INFO (YES && XMPP_LOG_ASYNC_ENABLED) #define XMPP_LOG_ASYNC_VERBOSE (YES && XMPP_LOG_ASYNC_ENABLED) #define XMPP_LOG_ASYNC_TRACE (YES && XMPP_LOG_ASYNC_ENABLED) // Define logging primitives. #define XMPPLogError(frmt, ...) LOG_OBJC_MAYBE(XMPP_LOG_ASYNC_ERROR, xmppLogLevel, XMPP_LOG_FLAG_ERROR, \ XMPP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define XMPPLogWarn(frmt, ...) LOG_OBJC_MAYBE(XMPP_LOG_ASYNC_WARN, xmppLogLevel, XMPP_LOG_FLAG_WARN, \ XMPP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define XMPPLogInfo(frmt, ...) LOG_OBJC_MAYBE(XMPP_LOG_ASYNC_INFO, xmppLogLevel, XMPP_LOG_FLAG_INFO, \ XMPP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define XMPPLogVerbose(frmt, ...) LOG_OBJC_MAYBE(XMPP_LOG_ASYNC_VERBOSE, xmppLogLevel, XMPP_LOG_FLAG_VERBOSE, \ XMPP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define XMPPLogTrace() LOG_OBJC_MAYBE(XMPP_LOG_ASYNC_TRACE, xmppLogLevel, XMPP_LOG_FLAG_TRACE, \ XMPP_LOG_CONTEXT, @"%@: %@", THIS_FILE, THIS_METHOD) #define XMPPLogTrace2(frmt, ...) LOG_OBJC_MAYBE(XMPP_LOG_ASYNC_TRACE, xmppLogLevel, XMPP_LOG_FLAG_TRACE, \ XMPP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define XMPPLogCError(frmt, ...) LOG_C_MAYBE(XMPP_LOG_ASYNC_ERROR, xmppLogLevel, XMPP_LOG_FLAG_ERROR, \ XMPP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define XMPPLogCWarn(frmt, ...) LOG_C_MAYBE(XMPP_LOG_ASYNC_WARN, xmppLogLevel, XMPP_LOG_FLAG_WARN, \ XMPP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define XMPPLogCInfo(frmt, ...) LOG_C_MAYBE(XMPP_LOG_ASYNC_INFO, xmppLogLevel, XMPP_LOG_FLAG_INFO, \ XMPP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define XMPPLogCVerbose(frmt, ...) LOG_C_MAYBE(XMPP_LOG_ASYNC_VERBOSE, xmppLogLevel, XMPP_LOG_FLAG_VERBOSE, \ XMPP_LOG_CONTEXT, frmt, ##__VA_ARGS__) #define XMPPLogCTrace() LOG_C_MAYBE(XMPP_LOG_ASYNC_TRACE, xmppLogLevel, XMPP_LOG_FLAG_TRACE, \ XMPP_LOG_CONTEXT, @"%@: %s", THIS_FILE, __FUNCTION__) #define XMPPLogCTrace2(frmt, ...) LOG_C_MAYBE(XMPP_LOG_ASYNC_TRACE, xmppLogLevel, XMPP_LOG_FLAG_TRACE, \ XMPP_LOG_CONTEXT, frmt, ##__VA_ARGS__) // Setup logging for XMPPStream (and subclasses such as XMPPStreamFacebook) #define XMPP_LOG_FLAG_SEND (1 << 5) #define XMPP_LOG_FLAG_RECV_PRE (1 << 6) // Prints data before it goes to the parser #define XMPP_LOG_FLAG_RECV_POST (1 << 7) // Prints data as it comes out of the parser #define XMPP_LOG_FLAG_SEND_RECV (XMPP_LOG_FLAG_SEND | XMPP_LOG_FLAG_RECV_POST) #define XMPP_LOG_SEND (xmppLogLevel & XMPP_LOG_FLAG_SEND) #define XMPP_LOG_RECV_PRE (xmppLogLevel & XMPP_LOG_FLAG_RECV_PRE) #define XMPP_LOG_RECV_POST (xmppLogLevel & XMPP_LOG_FLAG_RECV_POST) #define XMPP_LOG_ASYNC_SEND (YES && XMPP_LOG_ASYNC_ENABLED) #define XMPP_LOG_ASYNC_RECV_PRE (YES && XMPP_LOG_ASYNC_ENABLED) #define XMPP_LOG_ASYNC_RECV_POST (YES && XMPP_LOG_ASYNC_ENABLED) #define XMPPLogSend(format, ...) LOG_OBJC_MAYBE(XMPP_LOG_ASYNC_SEND, xmppLogLevel, XMPP_LOG_FLAG_SEND, \ XMPP_LOG_CONTEXT, format, ##__VA_ARGS__) #define XMPPLogRecvPre(format, ...) LOG_OBJC_MAYBE(XMPP_LOG_ASYNC_RECV_PRE, xmppLogLevel, XMPP_LOG_FLAG_RECV_PRE, \ XMPP_LOG_CONTEXT, format, ##__VA_ARGS__) #define XMPPLogRecvPost(format, ...) LOG_OBJC_MAYBE(XMPP_LOG_ASYNC_RECV_POST, xmppLogLevel, XMPP_LOG_FLAG_RECV_POST, \ XMPP_LOG_CONTEXT, format, ##__VA_ARGS__)
04081337-xmpp
Core/XMPPLogging.h
Objective-C
bsd
8,224
#import <Foundation/Foundation.h> #import "XMPPElement.h" /** * The XMPPIQ class represents an <iq> element. * It extends XMPPElement, which in turn extends NSXMLElement. * All <iq> elements that go in and out of the * xmpp stream will automatically be converted to XMPPIQ objects. * * This class exists to provide developers an easy way to add functionality to IQ processing. * Simply add your own category to XMPPIQ to extend it with your own custom methods. **/ @interface XMPPIQ : XMPPElement /** * Converts an NSXMLElement to an XMPPIQ element in place (no memory allocations or copying) **/ + (XMPPIQ *)iqFromElement:(NSXMLElement *)element; /** * Creates and returns a new autoreleased XMPPIQ element. * If the type or elementID parameters are nil, those attributes will not be added. **/ + (XMPPIQ *)iq; + (XMPPIQ *)iqWithType:(NSString *)type to:(XMPPJID *)jid; + (XMPPIQ *)iqWithType:(NSString *)type to:(XMPPJID *)jid elementID:(NSString *)eid; + (XMPPIQ *)iqWithType:(NSString *)type to:(XMPPJID *)jid elementID:(NSString *)eid child:(NSXMLElement *)childElement; /** * Creates and returns a new XMPPIQ element. * If the type or elementID parameters are nil, those attributes will not be added. **/ - (id)init; - (id)initWithType:(NSString *)type to:(XMPPJID *)jid; - (id)initWithType:(NSString *)type to:(XMPPJID *)jid elementID:(NSString *)eid; - (id)initWithType:(NSString *)type to:(XMPPJID *)jid elementID:(NSString *)eid child:(NSXMLElement *)childElement; /** * Returns the type attribute of the IQ. * According to the XMPP protocol, the type should be one of 'get', 'set', 'result' or 'error'. * * This method converts the attribute to lowercase so * case-sensitive string comparisons are safe (regardless of server treatment). **/ - (NSString *)type; /** * Convenience methods for determining the IQ type. **/ - (BOOL)isGetIQ; - (BOOL)isSetIQ; - (BOOL)isResultIQ; - (BOOL)isErrorIQ; /** * Convenience method for determining if the IQ is of type 'get' or 'set'. **/ - (BOOL)requiresResponse; /** * The XMPP RFC has various rules for the number of child elements an IQ is allowed to have: * * - An IQ stanza of type "get" or "set" MUST contain one and only one child element. * - An IQ stanza of type "result" MUST include zero or one child elements. * - An IQ stanza of type "error" SHOULD include the child element contained in the * associated "get" or "set" and MUST include an <error/> child. * * The childElement returns the single non-error element, if one exists, or nil. * The childErrorElement returns the error element, if one exists, or nil. **/ - (NSXMLElement *)childElement; - (NSXMLElement *)childErrorElement; @end
04081337-xmpp
Core/XMPPIQ.h
Objective-C
bsd
2,695
#import "XMPPParser.h" #import <libxml/parserInternals.h> #if TARGET_OS_IPHONE #import "DDXMLPrivate.h" #endif // When the xmpp parser invokes a delegate method, such as xmppParser:didReadElement:, // it exposes itself to the possibility of exceptions mid-parse. // This aborts the current run loop, // and thus causes the parser to lose the rest of the data that was passed to it via the parseData method. // // The end result is that our parser will likely barf the next time it tries to parse data. // Probably with a "EndTag: '</' not found" error. // After this the xmpp stream would be closed. // // Now during development, it's probably good to be exposed to these exceptions so they can be tracked down and fixed. // But for release, we might not want these exceptions to break the xmpp stream. // So for release mode you may consider enabling the try/catch. #define USE_TRY_CATCH 0 #define CHECK_FOR_NULL(value) do { if(value == NULL) { xmlAbortDueToMemoryShortage(ctxt); return; } } while(false) #if !TARGET_OS_IPHONE static void recursiveAddChild(NSXMLElement *parent, xmlNodePtr childNode); #endif @implementation XMPPParser /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark iPhone /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #if TARGET_OS_IPHONE static void onDidReadRoot(XMPPParser *parser, xmlNodePtr root) { if([parser->delegate respondsToSelector:@selector(xmppParser:didReadRoot:)]) { // We first copy the root node. // We do this to allow the delegate to retain and make changes to the reported root // without affecting the underlying xmpp parser. // xmlCopyNode(const xmlNodePtr node, int extended) // // node: // the node to copy // extended: // if 1 do a recursive copy (properties, namespaces and children when applicable) // if 2 copy properties and namespaces (when applicable) xmlNodePtr rootCopy = xmlCopyNode(root, 2); DDXMLElement *rootCopyWrapper = [DDXMLElement nodeWithElementPrimitive:rootCopy owner:nil]; #if USE_TRY_CATCH @try { // If the delegate throws an exception that we don't catch, // this would cause our parser to abort, // and ignore the rest of the data that was passed to us in parseData. // // The end result is that our parser will likely barf the next time it tries to parse data. // Probably with a "EndTag: '</' not found" error. [parser->delegate xmppParser:parser didReadRoot:rootCopyWrapper]; } @catch (id exception) { /* Ignore */ } #else [parser->delegate xmppParser:parser didReadRoot:rootCopyWrapper]; #endif // Note: DDXMLElement will properly free the rootCopy when it's deallocated. } } static void onDidReadElement(XMPPParser *parser, xmlNodePtr child) { [DDXMLNode detachChild:child fromNode:child->parent]; DDXMLElement *childWrapper = [DDXMLElement nodeWithElementPrimitive:child owner:nil]; // Note: We want to detach the child from the root even if the delegate method isn't setup. // This prevents the doc from growing infinitely large. if([parser->delegate respondsToSelector:@selector(xmppParser:didReadElement:)]) { #if USE_TRY_CATCH @try { // If the delegate throws an exception that we don't catch, // this would cause our parser to abort, // and ignore the rest of the data that was passed to us in parseData. // // The end result is that our parser will likely barf the next time it tries to parse data. // Probably with a "EndTag: '</' not found" error. [parser->delegate xmppParser:parser didReadElement:childWrapper]; } @catch (id exception) { /* Ignore */ } #else [parser->delegate xmppParser:parser didReadElement:childWrapper]; #endif } // Note: DDXMLElement will properly free the child when it's deallocated. } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Mac /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #else static void setName(NSXMLElement *element, xmlNodePtr node) { // Remember: The NSString initWithUTF8String raises an exception if passed NULL if(node->name == NULL) { [element setName:@""]; return; } if((node->ns != NULL) && (node->ns->prefix != NULL)) { // E.g: <deusty:element xmlns:deusty="deusty.com"/> NSString *prefix = [[NSString alloc] initWithUTF8String:(const char *)node->ns->prefix]; NSString *name = [[NSString alloc] initWithUTF8String:(const char *)node->name]; NSString *elementName = [[NSString alloc] initWithFormat:@"%@:%@", prefix, name]; [element setName:elementName]; [elementName release]; [name release]; [prefix release]; } else { NSString *elementName = [[NSString alloc] initWithUTF8String:(const char *)node->name]; [element setName:elementName]; [elementName release]; } } static void addNamespaces(NSXMLElement *element, xmlNodePtr node) { // Remember: The NSString initWithUTF8String raises an exception if passed NULL xmlNsPtr nsNode = node->nsDef; while(nsNode != NULL) { if(nsNode->href == NULL) { // Namespace doesn't have a value! } else { NSXMLNode *ns = [[NSXMLNode alloc] initWithKind:NSXMLNamespaceKind]; if(nsNode->prefix != NULL) { NSString *nsName = [[NSString alloc] initWithUTF8String:(const char *)nsNode->prefix]; [ns setName:nsName]; [nsName release]; } else { // Default namespace. // E.g: xmlns="deusty.com" [ns setName:@""]; } NSString *nsValue = [[NSString alloc] initWithUTF8String:(const char *)nsNode->href]; [ns setStringValue:nsValue]; [nsValue release]; [element addNamespace:ns]; [ns release]; } nsNode = nsNode->next; } } static void addChildren(NSXMLElement *element, xmlNodePtr node) { // Remember: The NSString initWithUTF8String raises an exception if passed NULL xmlNodePtr childNode = node->children; while(childNode != NULL) { if(childNode->type == XML_ELEMENT_NODE) { recursiveAddChild(element, childNode); } else if(childNode->type == XML_TEXT_NODE) { if(childNode->content != NULL) { NSString *value = [[NSString alloc] initWithUTF8String:(const char *)childNode->content]; [element setStringValue:value]; [value release]; } } childNode = childNode->next; } } static void addAttributes(NSXMLElement *element, xmlNodePtr node) { // Remember: The NSString initWithUTF8String raises an exception if passed NULL xmlAttrPtr attrNode = node->properties; while(attrNode != NULL) { if(attrNode->name == NULL) { // Attribute doesn't have a name! } else if(attrNode->children == NULL) { // Attribute doesn't have a value node! } else if(attrNode->children->content == NULL) { // Attribute doesn't have a value! } else { NSXMLNode *attr = [[NSXMLNode alloc] initWithKind:NSXMLAttributeKind]; if((attrNode->ns != NULL) && (attrNode->ns->prefix != NULL)) { // E.g: <element xmlns:deusty="deusty.com" deusty:attr="value"/> NSString *prefix = [[NSString alloc] initWithUTF8String:(const char *)attrNode->ns->prefix]; NSString *name = [[NSString alloc] initWithUTF8String:(const char *)attrNode->name]; NSString *attrName = [[NSString alloc] initWithFormat:@"%@:%@", prefix, name]; [attr setName:attrName]; [attrName release]; [name release]; [prefix release]; } else { NSString *attrName = [[NSString alloc] initWithUTF8String:(const char *)attrNode->name]; [attr setName:attrName]; [attrName release]; } NSString *attrValue = [[NSString alloc] initWithUTF8String:(const char *)attrNode->children->content]; [attr setStringValue:attrValue]; [attrValue release]; [element addAttribute:attr]; [attr release]; } attrNode = attrNode->next; } } /** * Recursively adds all the child elements to the given parent. * * Note: This method is almost the same as nsxmlFromLibxml, with one important difference. * It doen't add any objects to the autorelease pool. **/ static void recursiveAddChild(NSXMLElement *parent, xmlNodePtr childNode) { // Remember: The NSString initWithUTF8String raises an exception if passed NULL NSXMLElement *child = [[NSXMLElement alloc] initWithKind:NSXMLElementKind]; setName(child, childNode); addNamespaces(child, childNode); addChildren(child, childNode); addAttributes(child, childNode); [parent addChild:child]; [child release]; } /** * Creates and returns an NSXMLElement from the given node. * Use this method after finding the root element, or root.child element. **/ static NSXMLElement* nsxmlFromLibxml(xmlNodePtr rootNode) { // Remember: The NSString initWithUTF8String raises an exception if passed NULL NSXMLElement *root = [[NSXMLElement alloc] initWithKind:NSXMLElementKind]; setName(root, rootNode); addNamespaces(root, rootNode); addChildren(root, rootNode); addAttributes(root, rootNode); return [root autorelease]; } static void onDidReadRoot(XMPPParser *parser, xmlNodePtr root) { if([parser->delegate respondsToSelector:@selector(xmppParser:didReadRoot:)]) { NSXMLElement *nsRoot = nsxmlFromLibxml(root); #if USE_TRY_CATCH @try { // If the delegate throws an exception that we don't catch, // this would cause our parser to abort, // and ignore the rest of the data that was passed to us in parseData. // // The end result is that our parser will likely barf the next time it tries to parse data. // Probably with a "EndTag: '</' not found" error. [parser->delegate xmppParser:parser didReadRoot:nsRoot]; } @catch (id exception) { /* Ignore */ } #else [parser->delegate xmppParser:parser didReadRoot:nsRoot]; #endif } } static void onDidReadElement(XMPPParser *parser, xmlNodePtr child) { if([parser->delegate respondsToSelector:@selector(xmppParser:didReadElement:)]) { NSXMLElement *nsChild = nsxmlFromLibxml(child); #if USE_TRY_CATCH @try { // If the delegate throws an exception that we don't catch, // this would cause our parser to abort, // and ignore the rest of the data that was passed to us in parseData. // // The end result is that our parser will likely barf the next time it tries to parse data. // Probably with a "EndTag: '</' not found" error. [parser->delegate xmppParser:parser didReadElement:nsChild]; } @catch (id exception) { /* Ignore */ } #else [parser->delegate xmppParser:parser didReadElement:nsChild]; #endif } // Note: We want to detach the child from the root even if the delegate method isn't setup. // This prevents the doc from growing infinitely large. // Detach and free child to keep memory footprint small xmlUnlinkNode(child); xmlFreeNode(child); } #endif /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Common /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * This method is called at the end of the xmlStartElement method. * This allows us to inspect the parser and xml tree, and determine if we need to invoke any delegate methods. **/ static void postStartElement(xmlParserCtxt *ctxt) { XMPPParser *parser = (XMPPParser *)ctxt->_private; parser->depth++; if(!(parser->hasReportedRoot) && (parser->depth == 1)) { // We've received the full root - report it to the delegate if(ctxt->myDoc) { xmlNodePtr root = xmlDocGetRootElement(ctxt->myDoc); if(root) { onDidReadRoot(parser, root); parser->hasReportedRoot = YES; } } } } /** * This method is called at the end of the xmlEndElement method. * This allows us to inspect the parser and xml tree, and determine if we need to invoke any delegate methods. **/ static void postEndElement(xmlParserCtxt *ctxt) { XMPPParser *parser = (XMPPParser *)ctxt->_private; parser->depth--; if(parser->depth == 1) { // End of full xmpp element. // That is, a child of the root element. // Extract the child, and pass it to the delegate. xmlDocPtr doc = ctxt->myDoc; xmlNodePtr root = xmlDocGetRootElement(doc); xmlNodePtr child = root->children; while(child != NULL) { if(child->type == XML_ELEMENT_NODE) { onDidReadElement(parser, child); // Exit while loop break; } child = child->next; } } else if(parser->depth == 0) { // End of the root element if([parser->delegate respondsToSelector:@selector(xmppParserDidEnd:)]) { [parser->delegate xmppParserDidEnd:parser]; } } } /** * We're screwed... **/ static void xmlAbortDueToMemoryShortage(xmlParserCtxt *ctxt) { XMPPParser *parser = (XMPPParser *)ctxt->_private; xmlStopParser(ctxt); if([parser->delegate respondsToSelector:@selector(xmppParser:didFail:)]) { NSString *errMsg = @"Unable to allocate memory in xmpp parser"; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; NSError *error = [NSError errorWithDomain:@"libxmlErrorDomain" code:1001 userInfo:info]; [parser->delegate xmppParser:parser didFail:error]; } } /** * SAX parser C-style callback. * Invoked when a new node element is started. **/ static void xmlStartElement(void *ctx, const xmlChar *nodeName, const xmlChar *nodePrefix, const xmlChar *nodeUri, int nb_namespaces, const xmlChar **namespaces, int nb_attributes, int nb_defaulted, const xmlChar **attributes) { int i, j; xmlNsPtr lastAddedNs = NULL; xmlParserCtxt *ctxt = (xmlParserCtxt *)ctx; // We store the parent node in the context's node pointer. // We keep this updated by "pushing" the node in the startElement method, // and "popping" the node in the endElement method. xmlNodePtr parent = ctxt->node; // Create the node xmlNodePtr newNode = xmlNewDocNode(ctxt->myDoc, NULL, nodeName, NULL); CHECK_FOR_NULL(newNode); // Add the node to the tree if(parent == NULL) { // Root node xmlAddChild((xmlNodePtr)ctxt->myDoc, newNode); } else { xmlAddChild(parent, newNode); } // Process the namespaces for(i = 0, j = 0; j < nb_namespaces; j++) { // Extract namespace prefix and uri const xmlChar *nsPrefix = namespaces[i++]; const xmlChar *nsUri = namespaces[i++]; // Create the namespace xmlNsPtr newNs = xmlNewNs(NULL, nsUri, nsPrefix); CHECK_FOR_NULL(newNs); // Add namespace to node. // Each node has a linked list of nodes (in the nsDef variable). // The linked list is forward only. // In other words, each ns has a next, but not a prev pointer. if (newNode->nsDef == NULL) { newNode->nsDef = lastAddedNs = newNs; } else if(lastAddedNs) { lastAddedNs->next = newNs; lastAddedNs = newNs; } if ((nodeUri != NULL) && (nodePrefix == nsPrefix)) { // This is the namespace for the node. // Example 1: the node was <stream:stream xmlns:stream="url"> and newNs is the stream:url namespace. // Example 2: the node was <starttls xmlns="url"> and newNs is the null:url namespace. newNode->ns = newNs; } } // Search for the node's namespace if it wasn't already found if ((nodeUri != NULL) && (newNode->ns == NULL)) { // xmlSearchNs(xmlDocPtr doc, xmlNodePtr node, const xmlChar *nameSpace) // // Search a Ns registered under a given name space for a document. // Recurse on the parents until it finds the defined namespace or return NULL otherwise. // The nameSpace parameter can be NULL, this is a search for the default namespace. newNode->ns = xmlSearchNs(ctxt->myDoc, parent, nodePrefix); if (newNode->ns == NULL) { // We use href==NULL in the case of an element creation where the namespace was not defined. newNode->ns = xmlNewNs(newNode, NULL, nodePrefix); CHECK_FOR_NULL(newNode->ns); } } // Process all the attributes for (i = 0, j = 0; j < nb_attributes; j++) { const xmlChar *attrName = attributes[i++]; const xmlChar *attrPrefix = attributes[i++]; const xmlChar *attrUri = attributes[i++]; const xmlChar *valueBegin = attributes[i++]; const xmlChar *valueEnd = attributes[i++]; // The attribute value might contain character references which need to be decoded. // // "Franks &#38; Beans" -> "Franks & Beans" xmlChar *value = xmlStringLenDecodeEntities(ctxt, // the parser context valueBegin, // the input string (int)(valueEnd - valueBegin), // the input string length (XML_SUBSTITUTE_REF), // what to substitue 0, 0, 0); // end markers, 0 if none CHECK_FOR_NULL(value); if ((attrPrefix == NULL) && (attrUri == NULL)) { // Normal attribute - no associated namespace xmlAttrPtr newAttr = xmlNewProp(newNode, attrName, value); CHECK_FOR_NULL(newAttr); } else { // Find the namespace for the attribute xmlNsPtr attrNs = xmlSearchNs(ctxt->myDoc, newNode, attrPrefix); if(attrNs != NULL) { xmlAttrPtr newAttr = xmlNewNsProp(newNode, attrNs, attrName, value); CHECK_FOR_NULL(newAttr); } else { attrNs = xmlNewNs(NULL, NULL, nodePrefix); CHECK_FOR_NULL(attrNs); xmlAttrPtr newAttr = xmlNewNsProp(newNode, attrNs, attrName, value); CHECK_FOR_NULL(newAttr); } } xmlFree(value); } // Update our parent node pointer ctxt->node = newNode; // Invoke delegate methods if needed postStartElement(ctxt); } /** * SAX parser C-style callback. * Invoked when characters are found within a node. **/ static void xmlCharacters(void *ctx, const xmlChar *ch, int len) { xmlParserCtxt *ctxt = (xmlParserCtxt *)ctx; if(ctxt->node != NULL) { xmlNodePtr textNode = xmlNewTextLen(ch, len); // xmlAddChild(xmlNodePtr parent, xmlNodePtr cur) // // Add a new node to @parent, at the end of the child list // merging adjacent TEXT nodes (in which case @cur is freed). xmlAddChild(ctxt->node, textNode); } } /** * SAX parser C-style callback. * Invoked when a new node element is ended. **/ static void xmlEndElement(void *ctx, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI) { xmlParserCtxt *ctxt = (xmlParserCtxt *)ctx; // Update our parent node pointer if(ctxt->node != NULL) ctxt->node = ctxt->node->parent; // Invoke delegate methods if needed postEndElement(ctxt); } - (id)initWithDelegate:(id)aDelegate { if((self = [super init])) { delegate = aDelegate; hasReportedRoot = NO; depth = 0; // Create SAX handler xmlSAXHandler saxHandler; memset(&saxHandler, 0, sizeof(xmlSAXHandler)); saxHandler.initialized = XML_SAX2_MAGIC; saxHandler.startElementNs = xmlStartElement; saxHandler.characters = xmlCharacters; saxHandler.endElementNs = xmlEndElement; // Create the push parser context parserCtxt = xmlCreatePushParserCtxt(&saxHandler, NULL, NULL, 0, NULL); // Note: This method copies the saxHandler, so we don't have to keep it around. // Create the document to hold the parsed elements parserCtxt->myDoc = xmlNewDoc(parserCtxt->version); // Store reference to ourself parserCtxt->_private = self; // Note: The parserCtxt also has a userData variable, but it is used by the DOM building functions. // If we put a value there, it actually causes a crash! // We need to be sure to use the _private variable which libxml won't touch. } return self; } - (void)dealloc { if(parserCtxt) { // The xmlFreeParserCtxt method will not free the created document in parserCtxt->myDoc. if(parserCtxt->myDoc) { // Free the created xmlDoc xmlFreeDoc(parserCtxt->myDoc); } xmlFreeParserCtxt(parserCtxt); } [super dealloc]; } - (id)delegate { return delegate; } - (void)setDelegate:(id)aDelegate { delegate = aDelegate; } - (void)parseData:(NSData *)data { // The xmlParseChunk method below will cause the delegate methods to be invoked before this method returns. // If the delegate subsequently attempts to release us in one of those methods, and our dealloc method // gets invoked, then the parserCtxt will be freed in the middle of the xmlParseChunk method. // This often has the effect of crashing the application. // To get around this problem we simply retain/release within the method. [self retain]; int result = xmlParseChunk(parserCtxt, (const char *)[data bytes], (int)[data length], 0); if(result != 0) { if([delegate respondsToSelector:@selector(xmppParser:didFail:)]) { NSError *error; xmlError *xmlErr = xmlCtxtGetLastError(parserCtxt); if(xmlErr->message) { NSString *errMsg = [NSString stringWithFormat:@"%s", xmlErr->message]; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; error = [NSError errorWithDomain:@"libxmlErrorDomain" code:xmlErr->code userInfo:info]; } else { error = [NSError errorWithDomain:@"libxmlErrorDomain" code:xmlErr->code userInfo:nil]; } [delegate xmppParser:self didFail:error]; } } [self release]; } @end
04081337-xmpp
Core/XMPPParser.m
Objective-C
bsd
21,826
#import "XMPPIQ.h" #import "XMPPJID.h" #import "NSXMLElement+XMPP.h" #import <objc/runtime.h> @implementation XMPPIQ + (void)initialize { // We use the object_setClass method below to dynamically change the class from a standard NSXMLElement. // The size of the two classes is expected to be the same. // // If a developer adds instance methods to this class, bad things happen at runtime that are very hard to debug. // This check is here to aid future developers who may make this mistake. // // For Fearless And Experienced Objective-C Developers: // It may be possible to support adding instance variables to this class if you seriously need it. // To do so, try realloc'ing self after altering the class, and then initialize your variables. size_t superSize = class_getInstanceSize([NSXMLElement class]); size_t ourSize = class_getInstanceSize([XMPPIQ class]); if (superSize != ourSize) { NSLog(@"Adding instance variables to XMPPIQ is not currently supported!"); exit(15); } } + (XMPPIQ *)iqFromElement:(NSXMLElement *)element { object_setClass(element, [XMPPIQ class]); return (XMPPIQ *)element; } + (XMPPIQ *)iq { return [[[XMPPIQ alloc] initWithType:nil to:nil elementID:nil child:nil] autorelease]; } + (XMPPIQ *)iqWithType:(NSString *)type to:(XMPPJID *)jid { return [[[XMPPIQ alloc] initWithType:type to:jid elementID:nil child:nil] autorelease]; } + (XMPPIQ *)iqWithType:(NSString *)type to:(XMPPJID *)jid elementID:(NSString *)eid { return [[[XMPPIQ alloc] initWithType:type to:jid elementID:eid child:nil] autorelease]; } + (XMPPIQ *)iqWithType:(NSString *)type to:(XMPPJID *)jid elementID:(NSString *)eid child:(NSXMLElement *)childElement { return [[[XMPPIQ alloc] initWithType:type to:jid elementID:eid child:childElement] autorelease]; } - (id)init { return [self initWithType:nil to:nil elementID:nil child:nil]; } - (id)initWithType:(NSString *)type to:(XMPPJID *)jid { return [self initWithType:type to:jid elementID:nil child:nil]; } - (id)initWithType:(NSString *)type to:(XMPPJID *)jid elementID:(NSString *)eid { return [self initWithType:type to:jid elementID:eid child:nil]; } - (id)initWithType:(NSString *)type to:(XMPPJID *)jid elementID:(NSString *)eid child:(NSXMLElement *)childElement { if ((self = [super initWithName:@"iq"])) { if (type) [self addAttributeWithName:@"type" stringValue:type]; if (jid) [self addAttributeWithName:@"to" stringValue:[jid full]]; if (eid) [self addAttributeWithName:@"id" stringValue:eid]; if (childElement) [self addChild:childElement]; } return self; } - (NSString *)type { return [[self attributeStringValueForName:@"type"] lowercaseString]; } - (BOOL)isGetIQ { return [[self type] isEqualToString:@"get"]; } - (BOOL)isSetIQ { return [[self type] isEqualToString:@"set"]; } - (BOOL)isResultIQ { return [[self type] isEqualToString:@"result"]; } - (BOOL)isErrorIQ { return [[self type] isEqualToString:@"error"]; } - (BOOL)requiresResponse { // An entity that receives an IQ request of type "get" or "set" MUST reply with an IQ response // of type "result" or "error" (the response MUST preserve the 'id' attribute of the request). return [self isGetIQ] || [self isSetIQ]; } - (NSXMLElement *)childElement { NSArray *children = [self children]; for (NSXMLElement *child in children) { if ([[child name] caseInsensitiveCompare:@"error"] != NSOrderedSame) { return child; } } return nil; } - (NSXMLElement *)childErrorElement { NSArray *children = [self children]; for (NSXMLElement *child in children) { if ([[child name] caseInsensitiveCompare:@"error"] == NSOrderedSame) { return child; } } return nil; } @end
04081337-xmpp
Core/XMPPIQ.m
Objective-C
bsd
3,713
package cx.hell.android.pdfview; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.Arrays; import java.util.Comparator; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; /** * Minimalistic file browser. */ public class ChooseFileActivity extends Activity implements OnItemClickListener { /** * Logging tag. */ private final static String TAG = "cx.hell.android.pdfview"; private String currentPath = Environment.getExternalStorageDirectory().getAbsolutePath(); private TextView pathTextView = null; private ListView filesListView = null; private FileFilter fileFilter = null; private ArrayAdapter<String> fileListAdapter = null; private MenuItem aboutMenuItem = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.fileFilter = new FileFilter() { public boolean accept(File f) { return (f.isDirectory() || f.getName().toLowerCase().endsWith(".pdf")); } }; this.setContentView(R.layout.filechooser); this.pathTextView = (TextView) this.findViewById(R.id.path); this.filesListView = (ListView) this.findViewById(R.id.files); this.fileListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); this.filesListView.setAdapter(this.fileListAdapter); this.filesListView.setOnItemClickListener(this); this.update(); } /** * Reset list view and list adapter to reflect change to currentPath. */ private void update() { this.pathTextView.setText(this.currentPath); this.fileListAdapter.clear(); this.fileListAdapter.add(".."); File files[] = new File(this.currentPath).listFiles(this.fileFilter); if (files != null) { try { Arrays.sort(files, new Comparator<File>() { public int compare(File f1, File f2) { if (f1 == null) throw new RuntimeException("f1 is null inside sort"); if (f2 == null) throw new RuntimeException("f2 is null inside sort"); try { return f1.getName().toLowerCase().compareTo(f2.getName().toLowerCase()); } catch (NullPointerException e) { throw new RuntimeException("failed to compare " + f1 + " and " + f2, e); } } }); } catch (NullPointerException e) { throw new RuntimeException("failed to sort file list " + files + " for path " + this.currentPath, e); } for(int i = 0; i < files.length; ++i) this.fileListAdapter.add(files[i].getName()); } this.filesListView.setSelection(0); } @SuppressWarnings("rawtypes") public void onItemClick(AdapterView parent, View v, int position, long id) { String filename = (String) this.filesListView.getItemAtPosition(position); File clickedFile = null; try { clickedFile = new File(this.currentPath, filename).getCanonicalFile(); } catch (IOException e) { throw new RuntimeException(e); } if (clickedFile.isDirectory()) { Log.d(TAG, "change dir to " + clickedFile); this.currentPath = clickedFile.getAbsolutePath(); this.update(); } else { Log.i(TAG, "post intent to open file " + clickedFile); Intent intent = new Intent(); intent.setDataAndType(Uri.fromFile(clickedFile), "application/pdf"); intent.setClass(this, OpenFileActivity.class); intent.setAction("android.intent.action.VIEW"); this.startActivity(intent); } } @Override public boolean onOptionsItemSelected(MenuItem menuItem) { if (menuItem == this.aboutMenuItem) { Intent intent = new Intent(); intent.setClass(this, AboutPDFViewActivity.class); this.startActivity(intent); return true; } return false; } @Override public boolean onCreateOptionsMenu(Menu menu) { this.aboutMenuItem = menu.add("About"); return true; } }
0605tonton-test
pdfview/src/cx/hell/android/pdfview/ChooseFileActivity.java
Java
gpl3
4,483
/* * Copyright 2010 Ludovic Drolez * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package cx.hell.android.pdfview; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Class to manage the last opened page and bookmarks of PDF files * * @author Ludovic Drolez * */ public class Bookmark { /** db fields */ public static final String KEY_ID = "_id"; public static final String KEY_BOOK = "book"; public static final String KEY_NAME = "name"; public static final String KEY_PAGE = "page"; public static final String KEY_COMMENT = "comment"; public static final String KEY_TIME = "time"; private static final int DB_VERSION = 2; private static final String DATABASE_CREATE = "create table bookmark " + "(_id integer primary key autoincrement, " + "book text not null, name text not null, " + "page integer, comment text, time integer);"; private final Context context; private DatabaseHelper DBHelper; private SQLiteDatabase db; /** * Constructor * * @param ctx * application context */ public Bookmark(Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); } /** * Database helper class */ private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, "bookmark.db", null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion == 1) { db.execSQL("ALTER TABLE bookmark ADD COLUMN time integer"); } } } /** * open the bookmark database * * @return the Bookmark object * @throws SQLException */ public Bookmark open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } /** * close the database */ public void close() { DBHelper.close(); } /** * Set the last page seen for a file * * @param file * full file path * @param page * last page */ public void setLast(String file, int page) { String md5 = nameToMD5(file); ContentValues cv = new ContentValues(); cv.put(KEY_BOOK, md5); cv.put(KEY_PAGE, page); cv.put(KEY_NAME, "last"); cv.put(KEY_TIME, System.currentTimeMillis() / 1000); if (db.update("bookmark", cv, KEY_BOOK + "='" + md5 + "' AND " + KEY_NAME + "= 'last'", null) == 0) { db.insert("bookmark", null, cv); } } /** * Get the last recorded page for the given file * * @param file * @return page number (0-based) or 0 if not found */ public int getLast(String file) { int page = 0; String md5 = nameToMD5(file); Cursor cur = db.query(true, "bookmark", new String[] { KEY_PAGE }, KEY_BOOK + "='" + md5 + "' AND " + KEY_NAME + "= 'last'", null, null, null, null, "1"); if (cur != null) { if (cur.moveToFirst()) { page = cur.getInt(0); } } cur.close(); return page; } /** * Hash the file name to be sure that no strange characters will be in the * DB Can also later add the file size to the hash. * * @param file * path * @return md5 */ private String nameToMD5(String file) { // Create MD5 Hash MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); return ""; } digest.update(file.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) hexString.append(Integer.toHexString(0xFF & messageDigest[i])); return hexString.toString(); } }
0605tonton-test
pdfview/src/cx/hell/android/pdfview/Bookmark.java
Java
gpl3
4,596
package cx.hell.android.pdfview; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; /** * Displays "About..." info. */ public class AboutPDFViewActivity extends Activity { @Override public void onCreate(Bundle state) { super.onCreate(state); this.setContentView(R.layout.about); WebView v = (WebView)this.findViewById(R.id.webview_about); android.content.res.Resources resources = this.getResources(); InputStream aboutHtmlInputStream = new BufferedInputStream(resources.openRawResource(R.raw.about)); String aboutHtml = null; try { aboutHtml = StreamUtils.readStringFully(aboutHtmlInputStream); aboutHtmlInputStream.close(); aboutHtmlInputStream = null; resources = null; } catch (IOException e) { throw new RuntimeException(e); } v.loadData( aboutHtml, "text/html", "utf-8" ); } }
0605tonton-test
pdfview/src/cx/hell/android/pdfview/AboutPDFViewActivity.java
Java
gpl3
1,012
package cx.hell.android.pdfview; import java.io.IOException; import java.io.InputStream; import android.util.Log; import android.widget.ProgressBar; public class StreamUtils { public static byte[] readBytesFully(InputStream i) throws IOException { return StreamUtils.readBytesFully(i, 0, null); } public static byte[] readBytesFully(InputStream i, int max, ProgressBar progressBar) throws IOException { byte buf[] = new byte[4096]; int totalReadBytes = 0; while(true) { int readBytes = 0; readBytes = i.read(buf, totalReadBytes, buf.length-totalReadBytes); if (readBytes < 0) { // end of stream break; } totalReadBytes += readBytes; if (progressBar != null) progressBar.setProgress(totalReadBytes); if (max > 0 && totalReadBytes > max) { throw new IOException("Remote file is too big"); } if (totalReadBytes == buf.length) { // grow buf Log.d("cx.hell.android.pdfview", "readBytesFully: growing buffer from " + buf.length + " to " + (buf.length*2)); byte newbuf[] = new byte[buf.length*2]; System.arraycopy(buf, 0, newbuf, 0, totalReadBytes); buf = newbuf; } } byte result[] = new byte[totalReadBytes]; System.arraycopy(buf, 0, result, 0, totalReadBytes); return result; } public static String readStringFully(InputStream i) throws IOException { byte[] b = StreamUtils.readBytesFully(i); return new String(b, "utf-8"); } }
0605tonton-test
pdfview/src/cx/hell/android/pdfview/StreamUtils.java
Java
gpl3
1,470
package cx.hell.android.pdfview; import java.io.File; import java.io.FileDescriptor; import java.util.List; import cx.hell.android.lib.pagesview.FindResult; /** * Native PDF - interface to native code. */ public class PDF { static { System.loadLibrary("pdfview2"); } /** * Simple size class used in JNI to simplify parameter passing. * This shouldn't be used anywhere outide of pdf-related code. */ public static class Size implements Cloneable { public int width; public int height; public Size() { this.width = 0; this.height = 0; } public Size(int width, int height) { this.width = width; this.height = height; } public Size clone() { return new Size(this.width, this.height); } } /** * Holds pointer to native pdf_t struct. */ private int pdf_ptr = 0; /** * Parse bytes as PDF file and store resulting pdf_t struct in pdf_ptr. * @return error code */ synchronized private native int parseBytes(byte[] bytes); /** * Parse PDF file. * @param fileName pdf file name * @return error code */ synchronized private native int parseFile(String fileName); /** * Parse PDF file. * @param fd opened file descriptor * @return error code */ synchronized private native int parseFileDescriptor(FileDescriptor fd); /** * Construct PDF structures from bytes stored in memory. */ public PDF(byte[] bytes) { this.parseBytes(bytes); } /** * Construct PDF structures from file sitting on local filesystem. */ public PDF(File file) { this.parseFile(file.getAbsolutePath()); } /** * Construct PDF structures from opened file descriptor. * @param file opened file descriptor */ public PDF(FileDescriptor file) { this.parseFileDescriptor(file); } /** * Return page count from pdf_t struct. */ synchronized public native int getPageCount(); /** * Render a page. * @param n page number, starting from 0 * @param zoom page size scalling * @param left left edge * @param right right edge * @param passes requested size, used for size of resulting bitmap * @return bytes of bitmap in Androids format */ synchronized public native int[] renderPage(int n, int zoom, int left, int top, int rotation, PDF.Size rect); /** * Get PDF page size, store it in size struct, return error code. * @param n 0-based page number * @param size size struct that holds result * @return error code */ synchronized public native int getPageSize(int n, PDF.Size size); /** * Find text on given page, return list of find results. */ synchronized public native List<FindResult> find(String text, int page); /** * Clear search. */ synchronized public native void clearFindResult(); /** * Find text on page, return find results. */ synchronized public native List<FindResult> findOnPage(int page, String text); /** * Free memory allocated in native code. */ synchronized private native void freeMemory(); public void finalize() { this.freeMemory(); } }
0605tonton-test
pdfview/src/cx/hell/android/pdfview/PDF.java
Java
gpl3
3,160
package cx.hell.android.pdfview; /** * High level user-visible application exception. */ public class ApplicationException extends Exception { private static final long serialVersionUID = 3168318522532680977L; public ApplicationException(String message) { super(message); } }
0605tonton-test
pdfview/src/cx/hell/android/pdfview/ApplicationException.java
Java
gpl3
299
package cx.hell.android.pdfview; import java.io.File; import java.io.FileDescriptor; import java.io.FileNotFoundException; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ContentResolver; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.text.InputType; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import cx.hell.android.lib.pagesview.FindResult; import cx.hell.android.lib.pagesview.PagesView; /** * Document display activity. */ public class OpenFileActivity extends Activity { private final static String TAG = "cx.hell.android.pdfview"; private PDF pdf = null; private PagesView pagesView = null; private PDFPagesProvider pdfPagesProvider = null; private MenuItem aboutMenuItem = null; private MenuItem gotoPageMenuItem = null; private MenuItem rotateLeftMenuItem = null; private MenuItem rotateRightMenuItem = null; private MenuItem findTextMenuItem = null; private MenuItem clearFindTextMenuItem = null; private EditText pageNumberInputField = null; private EditText findTextInputField = null; private LinearLayout findButtonsLayout = null; private Button findPrevButton = null; private Button findNextButton = null; private Button findHideButton = null; // currently opened file path private String filePath = "/"; private String findText = null; private Integer currentFindResultPage = null; private Integer currentFindResultNumber = null; // zoom buttons, layout and fade animation private ImageButton zoomDownButton; private ImageButton zoomUpButton; private Animation zoomAnim; private LinearLayout zoomLayout; /** * Called when the activity is first created. * TODO: initialize dialog fast, then move file loading to other thread * TODO: add progress bar for file load * TODO: add progress icon for file rendering */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); // use a relative layout to stack the views RelativeLayout layout = new RelativeLayout(this); // the PDF view this.pagesView = new PagesView(this); this.pdf = this.getPDF(); this.pdfPagesProvider = new PDFPagesProvider(pdf); pagesView.setPagesProvider(pdfPagesProvider); layout.addView(pagesView); // the find buttons this.findButtonsLayout = new LinearLayout(this); this.findButtonsLayout.setOrientation(LinearLayout.HORIZONTAL); this.findButtonsLayout.setVisibility(View.GONE); this.findButtonsLayout.setGravity(Gravity.CENTER); this.findPrevButton = new Button(this); this.findPrevButton.setText("Prev"); this.findButtonsLayout.addView(this.findPrevButton); this.findNextButton = new Button(this); this.findNextButton.setText("Next"); this.findButtonsLayout.addView(this.findNextButton); this.findHideButton = new Button(this); this.findHideButton.setText("Hide"); this.findButtonsLayout.addView(this.findHideButton); this.setFindButtonHandlers(); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); lp.addRule(RelativeLayout.CENTER_HORIZONTAL); layout.addView(this.findButtonsLayout, lp); // the zoom buttons zoomLayout = new LinearLayout(this); zoomLayout.setOrientation(LinearLayout.HORIZONTAL); zoomDownButton = new ImageButton(this); zoomDownButton.setImageDrawable(getResources().getDrawable(R.drawable.btn_zoom_down)); zoomDownButton.setBackgroundColor(Color.TRANSPARENT); zoomLayout.addView(zoomDownButton, 80, 50); // TODO: remove hardcoded values zoomUpButton = new ImageButton(this); zoomUpButton.setImageDrawable(getResources().getDrawable(R.drawable.btn_zoom_up)); zoomUpButton.setBackgroundColor(Color.TRANSPARENT); zoomLayout.addView(zoomUpButton, 80, 50); zoomAnim = AnimationUtils.loadAnimation(this, R.anim.zoom); lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); setZoomButtonHandlers(); layout.addView(zoomLayout,lp); // display this this.setContentView(layout); // go to last viewed page gotoLastPage(); // send keyboard events to this view pagesView.setFocusable(true); pagesView.setFocusableInTouchMode(true); } /** * Save the current page before exiting */ @Override protected void onPause() { saveLastPage(); super.onPause(); } /** * Set handlers on findNextButton and findHideButton. */ private void setFindButtonHandlers() { this.findPrevButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { OpenFileActivity.this.findPrev(); } }); this.findNextButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { OpenFileActivity.this.findNext(); } }); this.findHideButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { OpenFileActivity.this.findHide(); } }); } /** * Set handlers on zoom level buttons */ private void setZoomButtonHandlers() { this.zoomDownButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { pagesView.zoomDown(); } }); this.zoomUpButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { pagesView.zoomUp(); } }); } /** * Return PDF instance wrapping file referenced by Intent. * Currently reads all bytes to memory, in future local files * should be passed to native code and remote ones should * be downloaded to local tmp dir. * @return PDF instance */ private PDF getPDF() { final Intent intent = getIntent(); Uri uri = intent.getData(); filePath = uri.getPath(); if (uri.getScheme().equals("file")) { return new PDF(new File(filePath)); } else if (uri.getScheme().equals("content")) { ContentResolver cr = this.getContentResolver(); FileDescriptor fileDescriptor; try { fileDescriptor = cr.openFileDescriptor(uri, "r").getFileDescriptor(); } catch (FileNotFoundException e) { throw new RuntimeException(e); // TODO: handle errors } return new PDF(fileDescriptor); } else { throw new RuntimeException("don't know how to get filename from " + uri); } } /** * Handle menu. * @param menuItem selected menu item * @return true if menu item was handled */ @Override public boolean onOptionsItemSelected(MenuItem menuItem) { if (menuItem == this.aboutMenuItem) { Intent intent = new Intent(); intent.setClass(this, AboutPDFViewActivity.class); this.startActivity(intent); return true; } else if (menuItem == this.gotoPageMenuItem) { this.showGotoPageDialog(); } else if (menuItem == this.rotateLeftMenuItem) { this.pagesView.rotate(-1); } else if (menuItem == this.rotateRightMenuItem) { this.pagesView.rotate(1); } else if (menuItem == this.findTextMenuItem) { this.showFindDialog(); } else if (menuItem == this.clearFindTextMenuItem) { this.clearFind(); } return false; } /** * Intercept touch events to handle the zoom buttons animation */ @Override public boolean dispatchTouchEvent(MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) { zoomAnim.setFillAfter(true); zoomLayout.startAnimation(zoomAnim); } return super.dispatchTouchEvent(event); }; /** * Hide the find buttons */ private void clearFind() { this.currentFindResultPage = null; this.currentFindResultNumber = null; this.pagesView.setFindMode(false); this.findButtonsLayout.setVisibility(View.GONE); } /** * Show error message to user. * @param message message to show */ private void errorMessage(String message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog dialog = builder.setMessage(message).setTitle("Error").create(); dialog.show(); } /** * Called from menu when user want to go to specific page. */ private void showGotoPageDialog() { final Dialog d = new Dialog(this); d.setTitle(R.string.goto_page_dialog_title); LinearLayout contents = new LinearLayout(this); contents.setOrientation(LinearLayout.VERTICAL); TextView label = new TextView(this); final int pagecount = this.pdfPagesProvider.getPageCount(); label.setText("Page number from " + 1 + " to " + pagecount); this.pageNumberInputField = new EditText(this); this.pageNumberInputField.setInputType(InputType.TYPE_CLASS_NUMBER); this.pageNumberInputField.setText("" + (this.pagesView.getCurrentPage() + 1)); Button goButton = new Button(this); goButton.setText(R.string.goto_page_go_button); goButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { int pageNumber = -1; try { pageNumber = Integer.parseInt(OpenFileActivity.this.pageNumberInputField.getText().toString())-1; } catch (NumberFormatException e) { /* ignore */ } d.dismiss(); if (pageNumber >= 0 && pageNumber < pagecount) { OpenFileActivity.this.gotoPage(pageNumber); } else { OpenFileActivity.this.errorMessage("Invalid page number"); } } }); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); params.leftMargin = 5; params.rightMargin = 5; params.bottomMargin = 2; params.topMargin = 2; contents.addView(label, params); contents.addView(pageNumberInputField, params); contents.addView(goButton, params); d.setContentView(contents); d.show(); } /** * Called after submitting go to page dialog. * @param page page number, 0-based */ private void gotoPage(int page) { Log.i(TAG, "rewind to page " + page); if (this.pagesView != null) { this.pagesView.scrollToPage(page); } } /** * Goto the last open page if possible */ private void gotoLastPage() { Bookmark b = new Bookmark(this.getApplicationContext()).open(); int lastpage = b.getLast(filePath); b.close(); if (lastpage > 0) { Handler mHandler = new Handler(); Runnable mUpdateTimeTask = new GotoPageThread(lastpage); mHandler.postDelayed(mUpdateTimeTask, 2000); } } /** * Save the last page in the bookmarks */ private void saveLastPage() { Bookmark b = new Bookmark(this.getApplicationContext()).open(); b.setLast(filePath, pagesView.getCurrentPage()); b.close(); Log.i(TAG, "last page saved for "+filePath); } /** * Create options menu, called by Android system. * @param menu menu to populate * @return true meaning that menu was populated */ @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); this.gotoPageMenuItem = menu.add(R.string.goto_page); this.rotateRightMenuItem = menu.add(R.string.rotate_page_left); this.rotateLeftMenuItem = menu.add(R.string.rotate_page_right); this.findTextMenuItem = menu.add(R.string.find_text); this.clearFindTextMenuItem = menu.add(R.string.clear_find_text); this.aboutMenuItem = menu.add(R.string.about); return true; } /** * Thread to delay the gotoPage action when opening a PDF file */ private class GotoPageThread implements Runnable { int page; public GotoPageThread(int page) { this.page = page; } public void run() { gotoPage(page); } } /** * Prepare menu contents. * Hide or show "Clear find results" menu item depending on whether * we're in find mode. * @param menu menu that should be prepared */ @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); this.clearFindTextMenuItem.setVisible(this.pagesView.getFindMode()); return true; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); Log.i(TAG, "onConfigurationChanged(" + newConfig + ")"); } /** * Show find dialog. * Very pretty UI code ;) */ private void showFindDialog() { Log.d(TAG, "find dialog..."); final Dialog dialog = new Dialog(this); dialog.setTitle(R.string.find_dialog_title); LinearLayout contents = new LinearLayout(this); contents.setOrientation(LinearLayout.VERTICAL); this.findTextInputField = new EditText(this); this.findTextInputField.setWidth(this.pagesView.getWidth() * 80 / 100); Button goButton = new Button(this); goButton.setText(R.string.find_go_button); goButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { String text = OpenFileActivity.this.findTextInputField.getText().toString(); OpenFileActivity.this.findText(text); dialog.dismiss(); } }); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); params.leftMargin = 5; params.rightMargin = 5; params.bottomMargin = 2; params.topMargin = 2; contents.addView(findTextInputField, params); contents.addView(goButton, params); dialog.setContentView(contents); dialog.show(); } private void findText(String text) { Log.d(TAG, "findText(" + text + ")"); this.findText = text; this.find(true); } /** * Called when user presses "next" button in find panel. */ private void findNext() { this.find(true); } /** * Called when user presses "prev" button in find panel. */ private void findPrev() { this.find(false); } /** * Called when user presses hide button in find panel. */ private void findHide() { if (this.pagesView != null) this.pagesView.setFindMode(false); this.currentFindResultNumber = null; this.currentFindResultPage = null; this.findButtonsLayout.setVisibility(View.GONE); } /** * Helper class that handles search progress, search cancelling etc. */ static class Finder implements Runnable, DialogInterface.OnCancelListener, DialogInterface.OnClickListener { private OpenFileActivity parent = null; private boolean forward; private AlertDialog dialog = null; private String text; private int startingPage; private int pageCount; private boolean cancelled = false; /** * Constructor for finder. * @param parent parent activity */ public Finder(OpenFileActivity parent, boolean forward) { this.parent = parent; this.forward = forward; this.text = parent.findText; this.pageCount = parent.pagesView.getPageCount(); if (parent.currentFindResultPage != null) { if (forward) { this.startingPage = (parent.currentFindResultPage + 1) % pageCount; } else { this.startingPage = (parent.currentFindResultPage - 1 + pageCount) % pageCount; } } else { this.startingPage = parent.pagesView.getCurrentPage(); } } public void setDialog(AlertDialog dialog) { this.dialog = dialog; } public void run() { int page = -1; this.createDialog(); this.showDialog(); for(int i = 0; i < this.pageCount; ++i) { if (this.cancelled) { this.dismissDialog(); return; } page = (startingPage + pageCount + (this.forward ? i : -i)) % this.pageCount; Log.d(TAG, "searching on " + page); this.updateDialog(page); List<FindResult> findResults = this.findOnPage(page); if (findResults != null && !findResults.isEmpty()) { Log.d(TAG, "found something at page " + page + ": " + findResults.size() + " results"); this.dismissDialog(); this.showFindResults(findResults, page); return; } } /* TODO: show "nothing found" message */ this.dismissDialog(); } /** * Called by finder thread to get find results for given page. * Routed to PDF instance. * If result is not empty, then finder loop breaks, current find position * is saved and find results are displayed. * @param page page to search on * @return results */ private List<FindResult> findOnPage(int page) { if (this.text == null) throw new IllegalStateException("text cannot be null"); return this.parent.pdf.find(this.text, page); } private void createDialog() { this.parent.runOnUiThread(new Runnable() { public void run() { String title = Finder.this.parent.getString(R.string.searching_for).replace("%1", Finder.this.text); String message = Finder.this.parent.getString(R.string.page_of).replace("%1", String.valueOf(Finder.this.startingPage)).replace("%2", String.valueOf(pageCount)); AlertDialog.Builder builder = new AlertDialog.Builder(Finder.this.parent); AlertDialog dialog = builder .setTitle(title) .setMessage(message) .setCancelable(true) .setNegativeButton(R.string.cancel, Finder.this) .create(); dialog.setOnCancelListener(Finder.this); Finder.this.dialog = dialog; } }); } public void updateDialog(final int page) { this.parent.runOnUiThread(new Runnable() { public void run() { String message = Finder.this.parent.getString(R.string.page_of).replace("%1", String.valueOf(page)).replace("%2", String.valueOf(pageCount)); Finder.this.dialog.setMessage(message); } }); } public void showDialog() { this.parent.runOnUiThread(new Runnable() { public void run() { Finder.this.dialog.show(); } }); } public void dismissDialog() { final AlertDialog dialog = this.dialog; this.parent.runOnUiThread(new Runnable() { public void run() { dialog.dismiss(); } }); } public void onCancel(DialogInterface dialog) { Log.d(TAG, "onCancel(" + dialog + ")"); this.cancelled = true; } public void onClick(DialogInterface dialog, int which) { Log.d(TAG, "onClick(" + dialog + ")"); this.cancelled = true; } private void showFindResults(final List<FindResult> findResults, final int page) { this.parent.runOnUiThread(new Runnable() { public void run() { int fn = Finder.this.forward ? 0 : findResults.size()-1; Finder.this.parent.currentFindResultPage = page; Finder.this.parent.currentFindResultNumber = fn; Finder.this.parent.pagesView.setFindResults(findResults); Finder.this.parent.pagesView.setFindMode(true); Finder.this.parent.pagesView.scrollToFindResult(fn); Finder.this.parent.findButtonsLayout.setVisibility(View.VISIBLE); Finder.this.parent.pagesView.invalidate(); } }); } }; /** * GUI for finding text. * Used both on initial search and for "next" and "prev" searches. * Displays dialog, handles cancel button, hides dialog as soon as * something is found. * @param */ private void find(boolean forward) { if (this.currentFindResultPage != null) { /* searching again */ int nextResultNum = forward ? this.currentFindResultNumber + 1 : this.currentFindResultNumber - 1; if (nextResultNum >= 0 && nextResultNum < this.pagesView.getFindResults().size()) { /* no need to really find - just focus on given result and exit */ this.currentFindResultNumber = nextResultNum; this.pagesView.scrollToFindResult(nextResultNum); this.pagesView.invalidate(); return; } } /* finder handles next/prev and initial search by itself */ Finder finder = new Finder(this, forward); Thread finderThread = new Thread(finder); finderThread.start(); } }
0605tonton-test
pdfview/src/cx/hell/android/pdfview/OpenFileActivity.java
Java
gpl3
21,073
package cx.hell.android.pdfview; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import android.graphics.Bitmap; import android.util.Log; import cx.hell.android.lib.pagesview.OnImageRenderedListener; import cx.hell.android.lib.pagesview.PagesProvider; import cx.hell.android.lib.pagesview.PagesView; import cx.hell.android.lib.pagesview.RenderingException; import cx.hell.android.lib.pagesview.Tile; /** * Provide rendered bitmaps of pages. */ public class PDFPagesProvider extends PagesProvider { /** * Const used by logging. */ private final static String TAG = "cx.hell.android.pdfview"; /** * Smart page-bitmap cache. * Stores up to approx MAX_CACHE_SIZE_BYTES of images. * Dynamically drops oldest unused bitmaps. * TODO: Return high resolution bitmaps if no exact res is available. * Bitmap images are tiled - tile size is specified in PagesView.TILE_SIZE. */ private static class BitmapCache { /** * Max size of bitmap cache in bytes. */ private static final int MAX_CACHE_SIZE_BYTES = 4*1024*1024; /** * Cache value - tuple with data and properties. */ private static class BitmapCacheValue { public Bitmap bitmap; /* public long millisAdded; */ public long millisAccessed; public BitmapCacheValue(Bitmap bitmap, long millisAdded) { this.bitmap = bitmap; /* this.millisAdded = millisAdded; */ this.millisAccessed = millisAdded; } } /** * Stores cached bitmaps. */ private Map<Tile, BitmapCacheValue> bitmaps; /** * Stats logging - number of cache hits. */ private long hits; /** * Stats logging - number of misses. */ private long misses; BitmapCache() { this.bitmaps = new HashMap<Tile, BitmapCacheValue>(); this.hits = 0; this.misses = 0; } /** * Get cached bitmap. Updates last access timestamp. * @param k cache key * @return bitmap found in cache or null if there's no matching bitmap */ Bitmap get(Tile k) { BitmapCacheValue v = this.bitmaps.get(k); Bitmap b = null; if (v != null) { // yeah b = v.bitmap; assert b != null; v.millisAccessed = System.currentTimeMillis(); this.hits += 1; } else { // le fu this.misses += 1; } if ((this.hits + this.misses) % 100 == 0 && (this.hits > 0 || this.misses > 0)) { Log.d("cx.hell.android.pdfview.pagecache", "hits: " + hits + ", misses: " + misses + ", hit ratio: " + (float)(hits) / (float)(hits+misses) + ", size: " + this.bitmaps.size()); } return b; } /** * Put rendered tile in cache. * @param tile tile definition (page, position etc), cache key * @param bitmap rendered tile contents, cache value */ synchronized void put(Tile tile, Bitmap bitmap) { while (this.willExceedCacheSize(bitmap) && !this.bitmaps.isEmpty()) { this.removeOldest(); } this.bitmaps.put(tile, new BitmapCacheValue(bitmap, System.currentTimeMillis())); } /** * Check if cache contains specified bitmap tile. Doesn't update last-used timestamp. * @return true if cache contains specified bitmap tile */ synchronized boolean contains(Tile tile) { return this.bitmaps.containsKey(tile); } /** * Estimate bitmap memory size. * This is just a guess. */ private static int getBitmapSizeInCache(Bitmap bitmap) { assert bitmap.getConfig() == Bitmap.Config.RGB_565; return bitmap.getWidth() * bitmap.getHeight() * 2; } /** * Get estimated sum of byte sizes of bitmaps stored in cache currently. */ private synchronized int getCurrentCacheSize() { int size = 0; Iterator<BitmapCacheValue> it = this.bitmaps.values().iterator(); while(it.hasNext()) { BitmapCacheValue bcv = it.next(); Bitmap bitmap = bcv.bitmap; size += getBitmapSizeInCache(bitmap); } return size; } /** * Determine if adding this bitmap would grow cache size beyond max size. */ private synchronized boolean willExceedCacheSize(Bitmap bitmap) { return (this.getCurrentCacheSize() + BitmapCache.getBitmapSizeInCache(bitmap) > MAX_CACHE_SIZE_BYTES); } /** * Remove oldest bitmap cache value. */ private void removeOldest() { Iterator<Tile> i = this.bitmaps.keySet().iterator(); long minmillis = 0; Tile oldest = null; while(i.hasNext()) { Tile k = i.next(); BitmapCacheValue v = this.bitmaps.get(k); if (oldest == null) { oldest = k; minmillis = v.millisAccessed; } else { if (minmillis > v.millisAccessed) { minmillis = v.millisAccessed; oldest = k; } } } if (oldest == null) throw new RuntimeException("couldnt find oldest"); BitmapCacheValue v = this.bitmaps.get(oldest); v.bitmap.recycle(); this.bitmaps.remove(oldest); } } private static class RendererWorker implements Runnable { /** * Worker stops rendering if error was encountered. */ private boolean isFailed = false; private PDFPagesProvider pdfPagesProvider; private Collection<Tile> tiles; /** * Internal worker number for debugging. */ private static int workerThreadId = 0; /** * Used as a synchronized flag. * If null, then there's no designated thread to render tiles. * There might be other worker threads running, but those have finished * their work and will finish really soon. * Only this one should pick up new jobs. */ private Thread workerThread = null; /** * Create renderer worker. * @param pdfPagesProvider parent pages provider */ RendererWorker(PDFPagesProvider pdfPagesProvider) { this.tiles = null; this.pdfPagesProvider = pdfPagesProvider; } /** * Called by outside world to provide more work for worker. * This also starts rendering thread if one is needed. * @param tiles a collection of tile objects, they carry information about what should be rendered next */ synchronized void setTiles(Collection<Tile> tiles) { this.tiles = tiles; if (this.workerThread == null) { Thread t = new Thread(this); t.setPriority(Thread.MIN_PRIORITY); t.setName("RendererWorkerThread#" + RendererWorker.workerThreadId++); this.workerThread = t; t.start(); Log.d(TAG, "started new worker thread"); } else { //Log.i(TAG, "setTiles notices tiles is not empty, that means RendererWorkerThread exists and there's no need to start new one"); } } /** * Get tiles that should be rendered next. May not block. * Also sets this.workerThread to null if there's no tiles to be rendered currently, * so that calling thread may finish. * If there are more tiles to be rendered, then this.workerThread is not reset. * @return some tiles */ synchronized Collection<Tile> popTiles() { if (this.tiles == null || this.tiles.isEmpty()) { this.workerThread = null; /* returning null, so calling thread will finish it's work */ return null; } Tile tile = this.tiles.iterator().next(); this.tiles.remove(tile); return Collections.singleton(tile); } /** * Thread's main routine. * There might be more than one running, but only one will get new tiles. Others * will get null returned by this.popTiles and will finish their work. */ public void run() { while(true) { if (this.isFailed) { Log.i(TAG, "RendererWorker is failed, exiting"); break; } Collection<Tile> tiles = this.popTiles(); /* this can't block */ if (tiles == null || tiles.size() == 0) break; try { Map<Tile,Bitmap> renderedTiles = this.pdfPagesProvider.renderTiles(tiles); this.pdfPagesProvider.publishBitmaps(renderedTiles); } catch (RenderingException e) { this.isFailed = true; this.pdfPagesProvider.publishRenderingException(e); } } } } private PDF pdf = null; private BitmapCache bitmapCache = null; private RendererWorker rendererWorker = null; private OnImageRenderedListener onImageRendererListener = null; public PDFPagesProvider(PDF pdf) { this.pdf = pdf; this.bitmapCache = new BitmapCache(); this.rendererWorker = new RendererWorker(this); } /** * Render tiles. * Called by worker, calls PDF's methods that in turn call native code. * @param tiles job description - what to render * @return mapping of jobs and job results, with job results being Bitmap objects */ private Map<Tile,Bitmap> renderTiles(Collection<Tile> tiles) throws RenderingException { Map<Tile,Bitmap> renderedTiles = new HashMap<Tile,Bitmap>(); Iterator<Tile> i = tiles.iterator(); Tile tile = null; while(i.hasNext()) { tile = i.next(); renderedTiles.put(tile, this.renderBitmap(tile)); } return renderedTiles; } /** * Really render bitmap. Takes time, should be done in background thread. Calls native code (through PDF object). */ private Bitmap renderBitmap(Tile tile) throws RenderingException { Bitmap b; PDF.Size size = new PDF.Size(PagesView.TILE_SIZE, PagesView.TILE_SIZE); int[] pagebytes = null; pagebytes = pdf.renderPage(tile.getPage(), tile.getZoom(), tile.getX(), tile.getY(), tile.getRotation(), size); /* native */ if (pagebytes == null) throw new RenderingException("Couldn't render page " + tile.getPage()); b = Bitmap.createBitmap(pagebytes, size.width, size.height, Bitmap.Config.ARGB_8888); /* simple tests show that this indeed works - memory usage is smaller with this extra copy */ /* TODO: make mupdf write directly to RGB_565 bitmap */ Bitmap btmp = b.copy(Bitmap.Config.RGB_565, true); if (btmp == null) throw new RuntimeException("bitmap copy failed"); b.recycle(); b = btmp; this.bitmapCache.put(tile, b); return b; } /** * Called by worker. */ private void publishBitmaps(Map<Tile,Bitmap> renderedTiles) { if (this.onImageRendererListener != null) { this.onImageRendererListener.onImagesRendered(renderedTiles); } else { Log.w(TAG, "we've got new bitmaps, but there's no one to notify about it!"); } } /** * Called by worker. */ private void publishRenderingException(RenderingException e) { if (this.onImageRendererListener != null) { this.onImageRendererListener.onRenderingException(e); } } @Override public void setOnImageRenderedListener(OnImageRenderedListener l) { this.onImageRendererListener = l; } /** * Get tile bitmap if it's already rendered. * @param tile which bitmap * @return rendered tile; tile represents rect of TILE_SIZE x TILE_SIZE pixels, * but might be of different size (should be scaled when painting) */ @Override public Bitmap getPageBitmap(Tile tile) { Bitmap b = null; b = this.bitmapCache.get(tile); if (b != null) return b; return null; } /** * Get page count. * @return number of pages */ @Override public int getPageCount() { int c = this.pdf.getPageCount(); if (c <= 0) throw new RuntimeException("failed to load pdf file: getPageCount returned " + c); return c; } /** * Get page sizes from pdf file. * @return array of page sizes */ @Override public int[][] getPageSizes() { int cnt = this.getPageCount(); int[][] sizes = new int[cnt][]; PDF.Size size = new PDF.Size(); int err; for(int i = 0; i < cnt; ++i) { err = this.pdf.getPageSize(i, size); if (err != 0) { throw new RuntimeException("failed to getPageSize(" + i + ",...), error: " + err); } sizes[i] = new int[2]; sizes[i][0] = size.width; sizes[i][1] = size.height; } return sizes; } /** * View informs provider what's currently visible. * Compute what should be rendered and pass that info to renderer worker thread, possibly waking up worker. * @param tiles specs of whats currently visible */ synchronized public void setVisibleTiles(Collection<Tile> tiles) { List<Tile> newtiles = null; for(Tile tile: tiles) { if (!this.bitmapCache.contains(tile)) { if (newtiles == null) newtiles = new LinkedList<Tile>(); newtiles.add(tile); } } if (newtiles != null) { this.rendererWorker.setTiles(newtiles); } } }
0605tonton-test
pdfview/src/cx/hell/android/pdfview/PDFPagesProvider.java
Java
gpl3
12,569
package cx.hell.android.lib.pagesview; /** * Tile definition. * Can be used as a key in maps (hashable, comparable). */ public class Tile { /** * X position of tile in pixels. */ private int x; /** * Y position of tile in pixels. */ private int y; private int zoom; private int page; private int rotation; int _hashCode; public Tile(int page, int zoom, int x, int y, int rotation) { this.page = page; this.zoom = zoom; this.x = x; this.y = y; this.rotation = rotation; } public String toString() { return "Tile(" + this.page + ", " + this.zoom + ", " + this.x + ", " + this.y + ", " + this.rotation + ")"; } public int hashCode() { return this._hashCode; } public boolean equals(Object o) { if (! (o instanceof Tile)) return false; Tile t = (Tile) o; return ( this._hashCode == t._hashCode && this.page == t.page && this.zoom == t.zoom && this.x == t.x && this.y == t.y && this.rotation == t.rotation ); } public int getPage() { return this.page; } public int getX() { return this.x; } public int getY() { return this.y; } public int getZoom() { return this.zoom; } public int getRotation() { return this.rotation; } }
0605tonton-test
pdfview/src/cx/hell/android/lib/pagesview/Tile.java
Java
gpl3
1,338
package cx.hell.android.lib.pagesview; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import android.graphics.Rect; import android.util.Log; /** * Find result. */ public class FindResult { /** * Logging tag. */ public static final String TAG = "cx.hell.android.pdfview"; /** * Page number. */ public int page; /** * List of rects that mark find result occurences. * In page dimensions (not scalled). */ public List<Rect> markers; /** * Add marker. */ public void addMarker(int x0, int y0, int x1, int y1) { if (x0 >= x1) throw new IllegalArgumentException("x0 must be smaller than x1: " + x0 + ", " + x1); if (y0 >= y1) throw new IllegalArgumentException("y0 must be smaller than y1: " + y0 + ", " + y1); if (this.markers == null) this.markers = new ArrayList<Rect>(); Rect nr = new Rect(x0, y0, x1, y1); if (this.markers.isEmpty()) { this.markers.add(nr); } else { this.markers.get(0).union(nr); } } public String toString() { StringBuilder b = new StringBuilder(); b.append("FindResult("); if (this.markers == null || this.markers.isEmpty()) { b.append("no markers"); } else { Iterator<Rect> i = this.markers.iterator(); Rect r = null; while(i.hasNext()) { r = i.next(); b.append(r); if (i.hasNext()) b.append(", "); } } b.append(")"); return b.toString(); } public void finalize() { Log.i(TAG, this + ".finalize()"); } }
0605tonton-test
pdfview/src/cx/hell/android/lib/pagesview/FindResult.java
Java
gpl3
1,538
package cx.hell.android.lib.pagesview; public class RenderingException extends Exception { private static final long serialVersionUID = 1010978161527539002L; public RenderingException(String message) { super(message); } }
0605tonton-test
pdfview/src/cx/hell/android/lib/pagesview/RenderingException.java
Java
gpl3
239
package cx.hell.android.lib.pagesview; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; /** * View that simplifies displaying of paged documents. * TODO: redesign zooms, pages, margins, layout * TODO: use more floats for better align, or use more ints for performance ;) (that is, really analyse what should be used when) */ public class PagesView extends View implements View.OnTouchListener, OnImageRenderedListener, View.OnKeyListener { /** * Tile size. */ public static final int TILE_SIZE = 256; /** * Logging tag. */ private static final String TAG = "cx.hell.android.pdfview"; // private final static int MAX_ZOOM = 4000; // private final static int MIN_ZOOM = 100; /** * Space between screen edge and page and between pages. */ private final static int MARGIN = 10; private Activity activity = null; /** * Source of page bitmaps. */ private PagesProvider pagesProvider = null; private long lastControlsUseMillis = 0; /** * Current width of this view. */ private int width = 0; /** * Current height of this view. */ private int height = 0; /** * Flag: are we being moved around by dragging. */ private boolean inDrag = false; /** * Drag start pos. */ private int dragx = 0; /** * Drag start pos. */ private int dragy = 0; /** * Drag pos. */ private int dragx1 = 0; /** * Drag pos. */ private int dragy1 = 0; /** * Position over book, not counting drag. * This is position of viewports center, not top-left corner. */ private int left = 0; /** * Position over book, not counting drag. * This is position of viewports center, not top-left corner. */ private int top = 0; /** * Current zoom level. * 1000 is 100%. */ private int zoomLevel = 1000; /** * Current rotation of pages. */ private int rotation = 0; /** * Base scalling factor - how much shrink (or grow) page to fit it nicely to screen at zoomLevel = 1000. * For example, if we determine that 200x400 image fits screen best, but PDF's pages are 400x800, then * base scaling would be 0.5, since at base scalling, without any zoom, page should fit into screen nicely. */ private float scalling0 = 0f; /** * Page sized obtained from pages provider. * These do not change. */ private int pageSizes[][]; /** * Find mode. */ private boolean findMode = false; /** * Paint used to draw find results. */ private Paint findResultsPaint = null; /** * Currently displayed find results. */ private List<FindResult> findResults = null; /** * hold the currently displayed page */ private int currentPage = 0; /** * avoid too much allocations in rectsintersect() */ private static Rect r1 = new Rect(); /** * Construct this view. * @param activity parent activity */ public PagesView(Activity activity) { super(activity); this.activity = activity; this.lastControlsUseMillis = System.currentTimeMillis(); this.findResultsPaint = new Paint(); this.findResultsPaint.setARGB(0xd0, 0xc0, 0, 0); this.findResultsPaint.setStyle(Paint.Style.FILL); this.findResultsPaint.setAntiAlias(true); this.findResultsPaint.setStrokeWidth(3); this.setOnTouchListener(this); this.setOnKeyListener(this); } /** * Handle size change event. * Update base scaling, move zoom controls to correct place etc. * @param w new width * @param h new height * @param oldw old width * @param oldh old height */ @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); this.width = w; this.height = h; if (this.scalling0 == 0f) { this.scalling0 = Math.min( ((float)this.height - 2*MARGIN) / (float)this.pageSizes[0][1], ((float)this.width - 2*MARGIN) / (float)this.pageSizes[0][0]); } if (oldw == 0 && oldh == 0) { this.left = this.width / 2; this.top = this.height / 2; } } public void setPagesProvider(PagesProvider pagesProvider) { this.pagesProvider = pagesProvider; if (this.pagesProvider != null) { this.pageSizes = this.pagesProvider.getPageSizes(); if (this.width > 0 && this.height > 0) { this.scalling0 = Math.min( ((float)this.height - 2*MARGIN) / (float)this.pageSizes[0][1], ((float)this.width - 2*MARGIN) / (float)this.pageSizes[0][0]); this.left = this.width / 2; this.top = this.height / 2; } } else { this.pageSizes = null; } this.pagesProvider.setOnImageRenderedListener(this); } /** * Draw view. * @param canvas what to draw on */ @Override public void onDraw(Canvas canvas) { this.drawPages(canvas); if (this.findMode) this.drawFindResults(canvas); } /** * Get current page width by page number taking into account zoom and rotation * @param pageno 0-based page number */ private int getCurrentPageWidth(int pageno) { float realpagewidth = (float)this.pageSizes[pageno][this.rotation % 2 == 0 ? 0 : 1]; float currentpagewidth = realpagewidth * scalling0 * (this.zoomLevel*0.001f); return (int)currentpagewidth; } /** * Get current page height by page number taking into account zoom and rotation. * @param pageno 0-based page number */ private float getCurrentPageHeight(int pageno) { float realpageheight = (float)this.pageSizes[pageno][this.rotation % 2 == 0 ? 1 : 0]; float currentpageheight = realpageheight * scalling0 * (this.zoomLevel*0.001f); return currentpageheight; } private float getCurrentMargin() { return (float)MARGIN * this.zoomLevel * 0.001f; } /** * This takes into account zoom level. */ private Point getPagePositionInDocumentWithZoom(int page) { float margin = this.getCurrentMargin(); float left = margin; float top = 0; for(int i = 0; i < page; ++i) { top += this.getCurrentPageHeight(i); } top += (page+1) * margin; return new Point((int)left, (int)top); } /** * Calculate screens (viewports) top-left corner position over document. */ private Point getScreenPositionOverDocument() { float top = this.top - this.height / 2; float left = this.left - this.width / 2; if (this.inDrag) { left -= (this.dragx1 - this.dragx); top -= (this.dragy1 - this.dragy); } return new Point((int)left, (int)top); } /** * Calculate current page position on screen in pixels. * @param page base-0 page number */ private Point getPagePositionOnScreen(int page) { if (page < 0) throw new IllegalArgumentException("page must be >= 0: " + page); if (page >= this.pageSizes.length) throw new IllegalArgumentException("page number too big: " + page); Point pagePositionInDocument = this.getPagePositionInDocumentWithZoom(page); Point screenPositionInDocument = this.getScreenPositionOverDocument(); return new Point( pagePositionInDocument.x - screenPositionInDocument.x, pagePositionInDocument.y - screenPositionInDocument.y ); } /** * Draw pages. * Also collect info what's visible and push this info to page renderer. */ private void drawPages(Canvas canvas) { Rect src = new Rect(); /* TODO: move out of drawPages */ Rect dst = new Rect(); /* TODO: move out of drawPages */ int pageWidth = 0; int pageHeight = 0; float pagex0, pagey0, pagex1, pagey1; // in doc, counts zoom float x, y; // on screen int dragoffx, dragoffy; int viewx0, viewy0; // view over doc LinkedList<Tile> visibleTiles = new LinkedList<Tile>(); float currentMargin = this.getCurrentMargin(); if (this.pagesProvider != null) { dragoffx = (inDrag) ? (dragx1 - dragx) : 0; dragoffy = (inDrag) ? (dragy1 - dragy) : 0; viewx0 = left - dragoffx - width/2; viewy0 = top - dragoffy - height/2; int pageCount = this.pageSizes.length; float currpageoff = currentMargin; this.currentPage = -1; for(int i = 0; i < pageCount; ++i) { // is page i visible? pageWidth = this.getCurrentPageWidth(i); pageHeight = (int) this.getCurrentPageHeight(i); pagex0 = currentMargin; pagex1 = (int)(currentMargin + pageWidth); pagey0 = currpageoff; pagey1 = (int)(currpageoff + pageHeight); if (rectsintersect( (int)pagex0, (int)pagey0, (int)pagex1, (int)pagey1, // page rect in doc viewx0, viewy0, viewx0 + this.width, viewy0 + this.height // viewport rect in doc )) { if (this.currentPage == -1) { // remember the currently displayed page this.currentPage = i; } x = pagex0 - viewx0; y = pagey0 - viewy0; for(int tileix = 0; tileix < pageWidth / TILE_SIZE + 1; ++tileix) for(int tileiy = 0; tileiy < pageHeight / TILE_SIZE + 1; ++tileiy) { dst.left = (int)(x + tileix*TILE_SIZE); dst.top = (int)(y + tileiy*TILE_SIZE); dst.right = dst.left + TILE_SIZE; dst.bottom = dst.top + TILE_SIZE; if (dst.intersects(0, 0, this.width, this.height)) { /* tile is visible */ Tile tile = new Tile(i, (int)(this.zoomLevel * scalling0), tileix*TILE_SIZE, tileiy*TILE_SIZE, this.rotation); Bitmap b = this.pagesProvider.getPageBitmap(tile); if (b != null) { //Log.d(TAG, " have bitmap: " + b + ", size: " + b.getWidth() + " x " + b.getHeight()); src.left = 0; src.top = 0; src.right = b.getWidth(); src.bottom = b.getWidth(); if (dst.right > x + pageWidth) { src.right = (int)(b.getWidth() * (float)((x+pageWidth)-dst.left) / (float)(dst.right - dst.left)); dst.right = (int)(x + pageWidth); } if (dst.bottom > y + pageHeight) { src.bottom = (int)(b.getHeight() * (float)((y+pageHeight)-dst.top) / (float)(dst.bottom - dst.top)); dst.bottom = (int)(y + pageHeight); } //this.fixOfscreen(dst, src); canvas.drawBitmap(b, src, dst, null); } visibleTiles.add(tile); } } } /* move to next page */ currpageoff += currentMargin + this.getCurrentPageHeight(i); } this.pagesProvider.setVisibleTiles(visibleTiles); } } /** * Draw find results. * TODO prettier icons * TODO message if nothing was found * @param canvas drawing target */ private void drawFindResults(Canvas canvas) { if (!this.findMode) throw new RuntimeException("drawFindResults but not in find results mode"); if (this.findResults == null || this.findResults.isEmpty()) { Log.w(TAG, "nothing found"); return; } for(FindResult findResult: this.findResults) { if (findResult.markers == null || findResult.markers.isEmpty()) throw new RuntimeException("illegal FindResult: find result must have at least one marker"); Iterator<Rect> i = findResult.markers.iterator(); Rect r = null; Point pagePosition = this.getPagePositionOnScreen(findResult.page); float pagex = pagePosition.x; float pagey = pagePosition.y; float z = (this.scalling0 * (float)this.zoomLevel * 0.001f); while(i.hasNext()) { r = i.next(); canvas.drawLine( r.left * z + pagex, r.top * z + pagey, r.left * z + pagex, r.bottom * z + pagey, this.findResultsPaint); canvas.drawLine( r.left * z + pagex, r.bottom * z + pagey, r.right * z + pagex, r.bottom * z + pagey, this.findResultsPaint); canvas.drawLine( r.right * z + pagex, r.bottom * z + pagey, r.right * z + pagex, r.top * z + pagey, this.findResultsPaint); // canvas.drawRect( // r.left * z + pagex, // r.top * z + pagey, // r.right * z + pagex, // r.bottom * z + pagey, // this.findResultsPaint); // Log.d(TAG, "marker lands on: " + // (r.left * z + pagex) + ", " + // (r.top * z + pagey) + ", " + // (r.right * z + pagex) + ", " + // (r.bottom * z + pagey) + ", "); } } } /** * Handle touch event coming from Android system. */ public boolean onTouch(View v, MotionEvent event) { this.lastControlsUseMillis = System.currentTimeMillis(); if (event.getAction() == MotionEvent.ACTION_DOWN) { Log.d(TAG, "onTouch(ACTION_DOWN)"); int x = (int)event.getX(); int y = (int)event.getY(); this.dragx = this.dragx1 = x; this.dragy = this.dragy1 = y; this.inDrag = true; } else if (event.getAction() == MotionEvent.ACTION_UP) { if (this.inDrag) { this.inDrag = false; this.left -= (this.dragx1 - this.dragx); this.top -= (this.dragy1 - this.dragy); } } else if (event.getAction() == MotionEvent.ACTION_MOVE) { if (this.inDrag) { this.dragx1 = (int) event.getX(); this.dragy1 = (int) event.getY(); this.invalidate(); } } return true; } /** * Handle keyboard events */ public boolean onKey(View v, int keyCode, KeyEvent event) { float step = 1.1f; if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DEL: case KeyEvent.KEYCODE_K: this.top -= this.getHeight() - 16; this.invalidate(); return true; case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_SPACE: case KeyEvent.KEYCODE_J: this.top += this.getHeight() - 16; this.invalidate(); return true; case KeyEvent.KEYCODE_H: this.left -= this.getWidth() / 4; this.invalidate(); return true; case KeyEvent.KEYCODE_L: this.left += this.getWidth() / 4; this.invalidate(); return true; case KeyEvent.KEYCODE_DPAD_LEFT: scrollToPage(currentPage - 1); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: scrollToPage(currentPage + 1); return true; case KeyEvent.KEYCODE_O: this.zoomLevel /= step; this.left /= step; this.top /= step; this.invalidate(); return true; case KeyEvent.KEYCODE_P: this.zoomLevel *= step; this.left *= step; this.top *= step; this.invalidate(); return true; } } return false; } /** * Test if specified rectangles intersect with each other. * Uses Androids standard Rect class. */ private static boolean rectsintersect( int r1x0, int r1y0, int r1x1, int r1y1, int r2x0, int r2y0, int r2x1, int r2y1) { r1.set(r1x0, r1y0, r1x1, r1y1); return r1.intersects(r2x0, r2y0, r2x1, r2y1); } /** * Used as a callback from pdf rendering code. * TODO: only invalidate what needs to be painted, not the whole view */ public void onImagesRendered(Map<Tile,Bitmap> renderedTiles) { Log.d(TAG, "there are " + renderedTiles.size() + " new rendered tiles"); this.post(new Runnable() { public void run() { PagesView.this.invalidate(); } }); } /** * Handle rendering exception. * Show error message and then quit parent activity. * TODO: find a proper way to finish an activity when something bad happens in view. */ public void onRenderingException(RenderingException reason) { final Activity activity = this.activity; final String message = reason.getMessage(); this.post(new Runnable() { public void run() { AlertDialog errorMessageDialog = new AlertDialog.Builder(activity) .setTitle("Error") .setMessage(message) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { activity.finish(); } }) .setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { activity.finish(); } }) .create(); errorMessageDialog.show(); } }); } /** * Move current viewport over n-th page. * Page is 0-based. * @param page 0-based page number */ synchronized public void scrollToPage(int page) { this.left = this.width / 2; float top = this.height / 2; for(int i = 0; i < page; ++i) { top += this.getCurrentPageHeight(i); } if (page > 0) top += (float)MARGIN * this.zoomLevel * 0.001f * (float)(page); this.top = (int)top; this.currentPage = page; this.invalidate(); } // /** // * Compute what's currently visible. // * @return collection of tiles that define what's currently visible // */ // private Collection<Tile> computeVisibleTiles() { // LinkedList<Tile> tiles = new LinkedList<Tile>(); // float viewx = this.left + (this.dragx1 - this.dragx); // float viewy = this.top + (this.dragy1 - this.dragy); // float pagex = MARGIN; // float pagey = MARGIN; // float pageWidth; // float pageHeight; // int tileix; // int tileiy; // int thisPageTileCountX; // int thisPageTileCountY; // float tilex; // float tiley; // for(int page = 0; page < this.pageSizes.length; ++page) { // // pageWidth = this.getCurrentPageWidth(page); // pageHeight = this.getCurrentPageHeight(page); // // thisPageTileCountX = (int)Math.ceil(pageWidth / TILE_SIZE); // thisPageTileCountY = (int)Math.ceil(pageHeight / TILE_SIZE); // // if (viewy + this.height < pagey) continue; /* before first visible page */ // if (viewx > pagey + pageHeight) break; /* after last page */ // // for(tileix = 0; tileix < thisPageTileCountX; ++tileix) { // for(tileiy = 0; tileiy < thisPageTileCountY; ++tileiy) { // tilex = pagex + tileix * TILE_SIZE; // tiley = pagey + tileiy * TILE_SIZE; // if (rectsintersect(viewx, viewy, viewx+this.width, viewy+this.height, // tilex, tiley, tilex+TILE_SIZE, tiley+TILE_SIZE)) { // tiles.add(new Tile(page, this.zoomLevel, (int)tilex, (int)tiley, this.rotation)); // } // } // } // // /* move to next page */ // pagey += this.getCurrentPageHeight(page) + MARGIN; // } // return tiles; // } // synchronized Collection<Tile> getVisibleTiles() { // return this.visibleTiles; // } /** * Rotate pages. * Updates rotation variable, then invalidates view. * @param rotation rotation */ synchronized public void rotate(int rotation) { this.rotation = (this.rotation + rotation) % 4; this.invalidate(); } /** * Set find mode. * @param m true if pages view should display find results and find controls */ synchronized public void setFindMode(boolean m) { if (this.findMode != m) { this.findMode = m; if (!m) { this.findResults = null; } } } /** * Return find mode. * @return find mode - true if view is currently in find mode */ public boolean getFindMode() { return this.findMode; } // /** // * Ask pages provider to focus on next find result. // * @param forward direction of search - true for forward, false for backward // */ // public void findNext(boolean forward) { // this.pagesProvider.findNext(forward); // this.scrollToFindResult(); // this.invalidate(); // } /** * Move viewport position to find result (if any). * Does not call invalidate(). */ public void scrollToFindResult(int n) { if (this.findResults == null || this.findResults.isEmpty()) return; Rect center = new Rect(); FindResult findResult = this.findResults.get(n); for(Rect marker: findResult.markers) { center.union(marker); } int page = findResult.page; int x = 0; int y = 0; for(int p = 0; p < page; ++p) { Log.d(TAG, "adding page " + p + " to y: " + this.pageSizes[p][1]); y += this.pageSizes[p][1]; } x += (center.left + center.right) / 2; y += (center.top + center.bottom) / 2; float margin = this.getCurrentMargin(); this.left = (int)(x * scalling0 * this.zoomLevel * 0.001f + margin); this.top = (int)(y * scalling0 * this.zoomLevel * 0.001f + (page+1)*margin); } /** * Get the current page number * * @return the current page. 0-based */ public int getCurrentPage() { return currentPage; } /** * Get page count. */ public int getPageCount() { return this.pageSizes.length; } /** * Set find results. */ public void setFindResults(List<FindResult> results) { this.findResults = results; } /** * Get current find results. */ public List<FindResult> getFindResults() { return this.findResults; } /** * Zoom down one level */ public void zoomDown() { float step = 1f/1.414f; this.zoomLevel *= step; this.left *= step; this.top *= step; Log.d(TAG, "zoom level changed to " + this.zoomLevel); this.invalidate(); } /** * Zoom up one level */ public void zoomUp() { float step = 1.414f; this.zoomLevel *= step; this.left *= step; this.top *= step; Log.d(TAG, "zoom level changed to " + this.zoomLevel); this.invalidate(); } }
0605tonton-test
pdfview/src/cx/hell/android/lib/pagesview/PagesView.java
Java
gpl3
21,553
package cx.hell.android.lib.pagesview; import java.util.Collection; import android.graphics.Bitmap; /** * Provide content of pages rendered by PagesView. */ public abstract class PagesProvider { /** * Get page image tile for drawing. */ public abstract Bitmap getPageBitmap(Tile tile); /** * Get page count. * This cannot change between executions - PagesView assumes (for now) that docuement doesn't change. */ public abstract int getPageCount(); /** * Get page sizes. * This cannot change between executions - PagesView assumes (for now) that docuement doesn't change. */ public abstract int[][] getPageSizes(); /** * Set notify target. * Usually page rendering takes some time. If image cannot be provided * immediately, provider may return null. * Then it's up to provider to notify view that requested image has arrived * and is ready to be drawn. * This function, if overridden, can be used to inform provider who * should be notifed. * Default implementation does nothing. */ public void setOnImageRenderedListener(OnImageRenderedListener listener) { /* to be overridden when needed */ } public abstract void setVisibleTiles(Collection<Tile> tiles); }
0605tonton-test
pdfview/src/cx/hell/android/lib/pagesview/PagesProvider.java
Java
gpl3
1,268
package cx.hell.android.lib.pagesview; import java.util.Map; import android.graphics.Bitmap; /** * Allow renderer to notify view that new bitmaps are ready. * Implemented by PagesView. */ public interface OnImageRenderedListener { void onImagesRendered(Map<Tile,Bitmap> renderedImages); void onRenderingException(RenderingException reason); }
0605tonton-test
pdfview/src/cx/hell/android/lib/pagesview/OnImageRenderedListener.java
Java
gpl3
365
<?xml version="1.0" encoding="UTF-8"?> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Android PDF Viewer</title> <style type="text/css"> body { font-family: sans-serif; font-size: 11pt; } </style> </head> <body> <h1>About APV</h1> <h2>Overview</h2> <p> APV is native PDF Viewer for Android Platform. </p> <p> APV project page is at <a href="http://apv.googlecode.com/">apv.googlecode.com</a>.<br/> You are welcome to report bugs at <a href="http://code.google.com/p/apv/issues/">code.google.com/p/apv/issues/</a>.<br/> There's also a user group at <a href="http://groups.google.com/group/android-pdf-viewer">groups.google.com/group/android-pdf-viewer</a>. </p> <h2>Keyboard shortcuts</h2> <ul> <li>DPad Right/Left: next/previous page</li> <li>DPad Down, Space: scroll down</li> <li>DPad Up, Delete: scroll up</li> <li>H, J, K, L: VI like motion keys</li> <li>O, P: Fine zoom</li> </ul> <h2>License / Libraries</h2> <p> APV is free software: you can redistribute it and/or modify it under the terms of the <a href="http://www.gnu.org/licenses/gpl.html">GNU General Public License</a> as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. </p> <p> APV uses following third party software: </p> <ul> <li> MuPDF library by Artifex Software, Inc. available at <a href="http://www.mupdf.com/">www.mupdf.com/</a></li> <li> This software is based in part on the work of the Independent JPEG Group. JPEG library is available at <a href="http://www.ijg.org/">www.ijg.org</a> </li> <li> FreeType2 library available at <a href="http://www.freetype.org/">www.freetype.org</a></li> <li> OpenJPEG library available at <a href="http://code.google.com/p/openjpeg/">http://code.google.com/p/openjpeg/</a>. OpenJPEG library is licensed under <a href="http://www.opensource.org/licenses/bsd-license.php">New BSD License</a>. </li> <li> jbig2dec library available at <a href="http://jbig2dec.sourceforge.net/">http://jbig2dec.sourceforge.net/</a>. jbig2dec is licensed under GPLv3. </li> </ul> <p>APV uses following third party media:</p> <ul> <li>btn_zoom_up and btn_zoom_down drawables that are part of Android Platform</li> </ul> <h2>Credits</h2> <p>APV is developed by</p> <ul> <li>Maciej Pietrzak <a href="mailto:maciej@hell.cx">maciej@hell.cx</a></li> <li>Ludovic Drolez <a href="mailto:ldrolez@gmail.com">ldrolez@gmail.com</a></li> <li>Naseer Ahmed <a href="mailto:naseer.ahmed@gmail.com">naseer.ahmed@gmail.com</a></li> <li>Riaz Ur Rahaman <a href="mailto:rahamanriaz@gmail.com">rahamanriaz@gmail.com</a></li> </ul> <h2>Donations</h2> <p> APV is free (like in freedom), but you can always show gratitude for our work by donating via PayPal. Dontations really make us feel appreciated, and when we feel appreciated, we are more likely to fix bugs (although we can't promise anything). If you'd like to donate, please click <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=LKB59NTKW9QLS">here</a>. </p> </body> </html>
0605tonton-test
pdfview/res/raw/about.html
HTML
gpl3
3,552
<?xml version="1.0" encoding="UTF-8"?> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Android PDF Viewer</title> <style type="text/css"> body { font-family: sans-serif; font-size: 11pt; } </style> </head> <body> <h1>O programie APV</h1> <h2>Wstęp</h2> <p> APV to natywny czytnik plików PDF dla platformy Android. </p> <p> Adres strony projektu APV to <a href="http://apv.googlecode.com/">apv.googlecode.com</a>.<br/> Zapraszamy do zgłaszania błędów na stronie <a href="http://code.google.com/p/apv/issues/">code.google.com/p/apv/issues/</a>.<br/> Istnieje również grupa użytkowników pod adresem <a href="http://groups.google.com/group/android-pdf-viewer">groups.google.com/group/android-pdf-viewer</a>. </p> <h2>Skróty klawiszowe</h2> <ul> <li>DPad Prawo/Left: następna/poprzednia strona</li> <li>DPad Dół, Spacja: przewijanie w dół</li> <li>DPad Góra, Delete: przewijanie w w górę</li> <li>H, J, K, L: przewijanie w stylu VI</li> <li>O, P: Fine zoom</li> </ul> <h2>Licencje / Biblioteki</h2> <p> APV is free software: you can redistribute it and/or modify it under the terms of the <a href="http://www.gnu.org/licenses/gpl.html">GNU General Public License</a> as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. </p> <p> APV wykorzystuje następujące oprogramowanie: </p> <ul> <li> Biblioteka MuPDF firmy Artifex Software, Inc. dostępna na <a href="http://www.mupdf.com/">www.mupdf.com</a> </li> <li> This software is based in part on the work of the Independent JPEG Group. JPEG library is available at <a href="http://www.ijg.org/">www.ijg.org</a> </li> <li> Biblioteka Freetype2 dostępna na <a href="http://www.freetype.org/">www.freetype.org</a> </li> <li> Biblioteka OpenJPEG dostępna na <a href="http://code.google.com/p/openjpeg/">http://code.google.com/p/openjpeg/</a>. Licencja biblioteki OpenJPEG to <a href="http://www.opensource.org/licenses/bsd-license.php">Nowa licencja BSD</a>. </li> <li> Biblioteka jbig2dec dostępna na <a href="http://jbig2dec.sourceforge.net/">http://jbig2dec.sourceforge.net/</a> na licencji GPLv3. </li> </ul> <p>APV wykorzystuje następujące pliki graficzne:</p> <ul> <li>obiekty <em>drawable</em> btn_zoom_up i btn_zoom_down pochodzące z projektu Android Platform</li> </ul> <h2>Autorzy</h2> <ul> <li>Maciej Pietrzak <a href="mailto:maciej@hell.cx">maciej@hell.cx</a></li> <li>Ludovic Drolez <a href="mailto:ldrolez@gmail.com">ldrolez@gmail.com</a></li> <li>Naseer Ahmed <a href="mailto:naseer.ahmed@gmail.com">naseer.ahmed@gmail.com</a></li> <li>Riaz Ur Rahaman <a href="mailto:rahamanriaz@gmail.com">rahamanriaz@gmail.com</a></li> </ul> <h2>Darowizny</h2> <p> APV jest dostępny za darmo dla wszystkich, ale jeśli chcesz, możesz wesprzeć projekt finansowo przez PayPal. Darowizny naprawdę poprawiają nam samopoczucie, a gdy się dobrze czujemy, istnieje większa szansa, że będziemy naprawiać błędy w aplikacji (aczkolwiek nic nie obiecujemy). Jeśli masz ochotę przekazać darowiznę, <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=LKB59NTKW9QLS">kliknij tutaj</a>, </p> </body> </html>
0605tonton-test
pdfview/res/raw-pl/about.html
HTML
gpl3
4,121
# adjust paths below and then run # . ./android-gcc-setup.sh # to setup build environment export NDK=/cygdrive/d/Code/android/android-ndk-r3 HOST_TYPE=windows ANDROID_VERSION=3 LIBDIR=$NDK/build/platforms/android-$ANDROID_VERSION/arch-arm/usr/lib export CFLAGS="-march=armv5te -mtune=xscale" export CC=$NDK/build/prebuilt/$HOST_TYPE/arm-eabi-4.2.1/bin/arm-eabi-gcc export CPPFLAGS=-I$NDK/build/platforms/android-$ANDROID_VERSION/arch-arm/usr/include export LDFLAGS="-L$LIBDIR -nostdlib -ldl -lc -lz $LIBDIR/crtbegin_static.o"
0605tonton-test
pdfview/scripts/android-gcc-setup.sh
Shell
gpl3
531
#!/bin/sh SCRIPTDIR=`dirname $0` . $SCRIPTDIR/android-gcc-setup.sh cd $SCRIPTDIR/.. if [ ! -d "deps" ] then mkdir -p deps fi cd deps DEPSDIR=$PWD JNIDIR=$DEPSDIR/../jni if [ ! -d "$JNIDIR/pdfview2/lib" ] then mkdir -p $JNIDIR/pdfview2/lib fi if [ ! -d "$JNIDIR/pdfview2/include" ] then mkdir -p $JNIDIR/pdfview2/include fi cd $DEPSDIR MUPDFSRC="mupdf-latest.tar.gz" FTSRC="freetype-2.3.11.tar.bz2" JPEGSRC="jpegsrc.v8a.tar.gz" MUPDF=$DEPSDIR/mupdf FT=$DEPSDIR/freetype-2.3.11 JPEG=$DEPSDIR/jpeg-8a echo "Downloading sources." if [ ! -e "$MUPDFSRC" ] then echo "Downloading mupdf..." wget http://ccxvii.net/mupdf/download/$MUPDFSRC -O $MUPDFSRC fi if [ ! -e "$FTSRC" ] then echo "Downloading freetype..." wget http://mirror.lihnidos.org/GNU/savannah/freetype/$FTSRC -O $FTSRC fi if [ ! -e "$JPEGSRC" ] then echo "Downloading jpeg..." wget http://www.ijg.org/files/$JPEGSRC -O $JPEGSRC fi rm -rf $MUPDF $FT $JPEG tar -xzvf $MUPDFSRC tar -xjvf $FTSRC tar -xzvf $JPEGSRC cd $FT sed -i -e '/^FT_COMPILE/s/\$(ANSIFLAGS) //' builds/freetype.mk ./configure --prefix="$FT/install" --host=arm-linux --disable-shared --enable-static make make install \cp install/lib/libfreetype.a $JNIDIR/pdfview2/lib \cp -rf include/* $JNIDIR/pdfview2/include cd $JPEG \cp *.c $JNIDIR/jpeg \cp *.h $JNIDIR/jpeg \cp jconfig.txt $JNIDIR/jpeg/jconfig.h unset CFLAGS unset CC unset CPPFLAGS unset LDFLAGS cd $MUPDF \cp mupdf/*.c $JNIDIR/mupdf/mupdf \cp mupdf/*.h $JNIDIR/mupdf/mupdf \cp fitz/*.c $JNIDIR/mupdf/fitz \cp fitz/*.h $JNIDIR/mupdf/fitz \cp fitzdraw/*.c $JNIDIR/mupdf/fitzdraw \cp -rf apps $JNIDIR/mupdf \cp -rf cmaps $JNIDIR/mupdf \cp -rf fonts $JNIDIR/mupdf cd $JNIDIR/mupdf/mupdf make -f APV.mk font_files cd $DEPSDIR/.. if [ ! -d "$NDK/apps/pdfview" ] then mkdir -p $NDK/apps/pdfview fi \cp -rf ndk-app/Application.mk $NDK/apps/pdfview/Application.mk sed -i -e "/APP_PROJECT_PATH/s|\/cygdrive.*|$PWD|g" $NDK/apps/pdfview/Application.mk cd $NDK make APP=pdfview
0605tonton-test
pdfview/scripts/build-native.sh
Shell
gpl3
2,006
/* * This is a modified version of pdf_debug.c file which is part of MuPDF * by Artifex Software, Inc. */ #include "fitz.h" #include "mupdf.h" static void (*pdf_loghandler)(const char *s) = NULL; static int reinit_pdflog = 0; /* * Enable logging by setting environment variable MULOG to: * (a)ll or a combination of * (x)ref (r)src (f)ont (i)mage (s)hade (p)age * * eg. MULOG=fis ./x11pdf mytestfile.pdf */ enum { PDF_LXREF = 1, PDF_LRSRC = 2, PDF_LFONT = 4, PDF_LIMAGE = 8, PDF_LSHADE = 16, PDF_LPAGE = 32 }; static inline void pdflog(int tag, char *name, char *fmt, va_list ap) { static int flags = 128; static int level = 0; static int push = 1; int i; if (flags == 128 || reinit_pdflog) { char *s = getenv("MULOG"); if (pdf_loghandler != NULL) s = "axrfisp"; flags = 0; if (s) { if (strstr(s, "a")) flags |= 0xffff; if (strstr(s, "x")) flags |= PDF_LXREF; if (strstr(s, "r")) flags |= PDF_LRSRC; if (strstr(s, "f")) flags |= PDF_LFONT; if (strstr(s, "i")) flags |= PDF_LIMAGE; if (strstr(s, "s")) flags |= PDF_LSHADE; if (strstr(s, "p")) flags |= PDF_LPAGE; } reinit_pdflog = 0; } if (!(flags & tag)) return; if (strchr(fmt, '}')) level --; if (push) { if (pdf_loghandler == NULL) { printf("%s: ", name); for (i = 0; i < level; i++) printf(" "); } } if (pdf_loghandler == NULL) { vprintf(fmt, ap); } else { char b[2048]; int ll = push ? level : 0; b[0] = 0; if (push) { strncat(b, name, 100); strncat(b, ": ", 100); } for(i = 0; i < ll; ++i) strncat(b, " ", 100); vsnprintf(b+strlen(b), 2048-strlen(b), fmt, ap); b[2047] = 0; pdf_loghandler(b); } if (strchr(fmt, '{')) level ++; push = !!strchr(fmt, '\n'); if (pdf_loghandler == NULL) fflush(stdout); } void pdf_logxref(char *fmt, ...) {va_list ap;va_start(ap,fmt);pdflog(PDF_LXREF,"xref",fmt,ap);va_end(ap);} void pdf_logrsrc(char *fmt, ...) {va_list ap;va_start(ap,fmt);pdflog(PDF_LRSRC,"rsrc",fmt,ap);va_end(ap);} void pdf_logfont(char *fmt, ...) {va_list ap;va_start(ap,fmt);pdflog(PDF_LFONT,"font",fmt,ap);va_end(ap);} void pdf_logimage(char *fmt, ...) {va_list ap;va_start(ap,fmt);pdflog(PDF_LIMAGE,"imag",fmt,ap);va_end(ap);} void pdf_logshade(char *fmt, ...) {va_list ap;va_start(ap,fmt);pdflog(PDF_LSHADE,"shad",fmt,ap);va_end(ap);} void pdf_logpage(char *fmt, ...) {va_list ap;va_start(ap,fmt);pdflog(PDF_LPAGE,"page",fmt,ap);va_end(ap);} void pdf_setloghandler(void (*newloghandler)(const char *)) { pdf_loghandler = newloghandler; reinit_pdflog = 1; }
0605tonton-test
pdfview/jni/mupdf/mupdf/apv_pdf_debug.c
C
gpl3
2,748
LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_C_INCLUDES := $(LOCAL_PATH)/../fitz $(LOCAL_PATH)/../../pdfview2/include LOCAL_MODULE := mupdf LOCAL_CFLAGS := -DNOCJK LOCAL_SRC_FILES := \ pdf_crypt.c \ apv_pdf_debug.c \ pdf_lex.c \ pdf_nametree.c \ pdf_parse.c \ pdf_repair.c \ pdf_stream.c \ pdf_xref.c \ pdf_annot.c \ pdf_outline.c \ pdf_cmap.c \ pdf_cmap_parse.c \ pdf_cmap_load.c \ pdf_cmap_table.c \ pdf_fontagl.c \ pdf_fontenc.c \ pdf_unicode.c \ pdf_font.c \ pdf_type3.c \ pdf_fontmtx.c \ pdf_fontfile.c \ pdf_function.c \ pdf_colorspace.c \ pdf_image.c \ pdf_pattern.c \ pdf_shade.c \ pdf_xobject.c \ pdf_build.c \ pdf_interpret.c \ pdf_page.c \ pdf_pagetree.c \ pdf_store.c \ \ font_misc.c \ font_mono.c \ font_sans.c \ font_serif.c \ # cmap_tounicode.c \ # font_cjk.c \ # cmap_cns.c \ # cmap_gb.c cmap_japan.c cmap_korea.c include $(BUILD_STATIC_LIBRARY) # vim: set sts=8 sw=8 ts=8 noet:
0605tonton-test
pdfview/jni/mupdf/mupdf/Android.mk
Makefile
gpl3
961
font_files: font_misc.c font_mono.c font_serif.c font_sans.c font_cjk.c cmap_tounicode.c cmap_cns.c cmap_gb.c cmap_japan.c cmap_korea.c clean: @rm -v font_misc.c font_mono.c font_serif.c font_sans.c font_cjk.c cmap_tounicode.c cmap_cns.c cmap_gb.c cmap_japan.c cmap_korea.c \ fontdump cmapdump cmapdump: cmapdump.c pdf_debug.c gcc -o cmapdump cmapdump.c pdf_debug.c -I../fitz fonttump: fontdump.c gcc -o fontdump fontdump.c font_misc.c: fontdump ./fontdump font_misc.c \ ../fonts/Dingbats.cff \ ../fonts/StandardSymL.cff \ ../fonts/URWChanceryL-MediItal.cff font_mono.c: fontdump ./fontdump font_mono.c \ ../fonts/NimbusMonL-Regu.cff \ ../fonts/NimbusMonL-ReguObli.cff \ ../fonts/NimbusMonL-Bold.cff \ ../fonts/NimbusMonL-BoldObli.cff font_sans.c: fontdump ./fontdump font_sans.c \ ../fonts/NimbusSanL-Bold.cff \ ../fonts/NimbusSanL-BoldItal.cff \ ../fonts/NimbusSanL-Regu.cff \ ../fonts/NimbusSanL-ReguItal.cff font_serif.c: fontdump ./fontdump font_serif.c \ ../fonts/NimbusRomNo9L-Regu.cff \ ../fonts/NimbusRomNo9L-ReguItal.cff \ ../fonts/NimbusRomNo9L-Medi.cff \ ../fonts/NimbusRomNo9L-MediItal.cff font_cjk.c: fontdump ./fontdump font_cjk.c \ ../fonts/droid/DroidSansFallback.ttf cmap_tounicode.c: cmapdump ./cmapdump cmap_tounicode.c \ ../cmaps/Adobe-CNS1-UCS2 \ ../cmaps/Adobe-GB1-UCS2 \ ../cmaps/Adobe-Japan1-UCS2 \ ../cmaps/Adobe-Korea1-UCS2 cmap_cns.c: cmapdump ./cmapdump cmap_cns.c \ ../cmaps/Adobe-CNS1-0 ../cmaps/Adobe-CNS1-1 ../cmaps/Adobe-CNS1-2 ../cmaps/Adobe-CNS1-3 \ ../cmaps/Adobe-CNS1-4 ../cmaps/Adobe-CNS1-5 ../cmaps/Adobe-CNS1-6 ../cmaps/B5-H ../cmaps/B5-V ../cmaps/B5pc-H ../cmaps/B5pc-V \ ../cmaps/CNS-EUC-H ../cmaps/CNS-EUC-V ../cmaps/CNS1-H ../cmaps/CNS1-V ../cmaps/CNS2-H ../cmaps/CNS2-V ../cmaps/ETen-B5-H \ ../cmaps/ETen-B5-V ../cmaps/ETenms-B5-H ../cmaps/ETenms-B5-V ../cmaps/ETHK-B5-H ../cmaps/ETHK-B5-V \ ../cmaps/HKdla-B5-H ../cmaps/HKdla-B5-V ../cmaps/HKdlb-B5-H ../cmaps/HKdlb-B5-V ../cmaps/HKgccs-B5-H \ ../cmaps/HKgccs-B5-V ../cmaps/HKm314-B5-H ../cmaps/HKm314-B5-V ../cmaps/HKm471-B5-H ../cmaps/HKm471-B5-V \ ../cmaps/HKscs-B5-H ../cmaps/HKscs-B5-V ../cmaps/UniCNS-UCS2-H ../cmaps/UniCNS-UCS2-V \ ../cmaps/UniCNS-UTF16-H ../cmaps/UniCNS-UTF16-V cmap_gb.c: cmapdump ./cmapdump cmap_gb.c \ ../cmaps/Adobe-GB1-0 ../cmaps/Adobe-GB1-1 ../cmaps/Adobe-GB1-2 ../cmaps/Adobe-GB1-3 ../cmaps/Adobe-GB1-4 \ ../cmaps/Adobe-GB1-5 ../cmaps/GB-EUC-H ../cmaps/GB-EUC-V ../cmaps/GB-H ../cmaps/GB-V ../cmaps/GBK-EUC-H ../cmaps/GBK-EUC-V \ ../cmaps/GBK2K-H ../cmaps/GBK2K-V ../cmaps/GBKp-EUC-H ../cmaps/GBKp-EUC-V ../cmaps/GBpc-EUC-H ../cmaps/GBpc-EUC-V \ ../cmaps/GBT-EUC-H ../cmaps/GBT-EUC-V ../cmaps/GBT-H ../cmaps/GBT-V ../cmaps/GBTpc-EUC-H ../cmaps/GBTpc-EUC-V \ ../cmaps/UniGB-UCS2-H ../cmaps/UniGB-UCS2-V ../cmaps/UniGB-UTF16-H ../cmaps/UniGB-UTF16-V cmap_japan.c: cmapdump ./cmapdump cmap_japan.c \ ../cmaps/78-EUC-H ../cmaps/78-EUC-V ../cmaps/78-H ../cmaps/78-RKSJ-H ../cmaps/78-RKSJ-V ../cmaps/78-V ../cmaps/78ms-RKSJ-H \ ../cmaps/78ms-RKSJ-V ../cmaps/83pv-RKSJ-H ../cmaps/90ms-RKSJ-H ../cmaps/90ms-RKSJ-V ../cmaps/90msp-RKSJ-H \ ../cmaps/90msp-RKSJ-V ../cmaps/90pv-RKSJ-H ../cmaps/90pv-RKSJ-V ../cmaps/Add-H ../cmaps/Add-RKSJ-H \ ../cmaps/Add-RKSJ-V ../cmaps/Add-V ../cmaps/Adobe-Japan1-0 ../cmaps/Adobe-Japan1-1 ../cmaps/Adobe-Japan1-2 \ ../cmaps/Adobe-Japan1-3 ../cmaps/Adobe-Japan1-4 ../cmaps/Adobe-Japan1-5 ../cmaps/Adobe-Japan1-6 \ ../cmaps/EUC-H ../cmaps/EUC-V ../cmaps/Ext-H ../cmaps/Ext-RKSJ-H ../cmaps/Ext-RKSJ-V ../cmaps/Ext-V ../cmaps/H ../cmaps/Hankaku \ ../cmaps/Hiragana ../cmaps/Katakana ../cmaps/NWP-H ../cmaps/NWP-V ../cmaps/RKSJ-H ../cmaps/RKSJ-V ../cmaps/Roman \ ../cmaps/UniJIS-UCS2-H ../cmaps/UniJIS-UCS2-HW-H ../cmaps/UniJIS-UCS2-HW-V ../cmaps/UniJIS-UCS2-V \ ../cmaps/UniJISPro-UCS2-HW-V ../cmaps/UniJISPro-UCS2-V ../cmaps/V ../cmaps/WP-Symbol \ ../cmaps/Adobe-Japan2-0 ../cmaps/Hojo-EUC-H ../cmaps/Hojo-EUC-V ../cmaps/Hojo-H ../cmaps/Hojo-V \ ../cmaps/UniHojo-UCS2-H ../cmaps/UniHojo-UCS2-V ../cmaps/UniHojo-UTF16-H ../cmaps/UniHojo-UTF16-V \ ../cmaps/UniJIS-UTF16-H ../cmaps/UniJIS-UTF16-V cmap_korea.c: cmapdump ./cmapdump cmap_korea.c \ ../cmaps/Adobe-Korea1-0 ../cmaps/Adobe-Korea1-1 ../cmaps/Adobe-Korea1-2 ../cmaps/KSC-EUC-H \ ../cmaps/KSC-EUC-V ../cmaps/KSC-H ../cmaps/KSC-Johab-H ../cmaps/KSC-Johab-V ../cmaps/KSC-V ../cmaps/KSCms-UHC-H \ ../cmaps/KSCms-UHC-HW-H ../cmaps/KSCms-UHC-HW-V ../cmaps/KSCms-UHC-V ../cmaps/KSCpc-EUC-H \ ../cmaps/KSCpc-EUC-V ../cmaps/UniKS-UCS2-H ../cmaps/UniKS-UCS2-V ../cmaps/UniKS-UTF16-H ../cmaps/UniKS-UTF16-V # vim: set sts=8 ts=8 sw=8 noet:
0605tonton-test
pdfview/jni/mupdf/mupdf/APV.mk
Makefile
gpl3
4,661
LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_C_INCLUDES := $(LOCAL_PATH)/../mupdf $(LOCAL_PATH)/../fitz LOCAL_MODULE := fitzdraw LOCAL_SRC_FILES := \ archport.c \ archarm.c \ blendmodes.c \ glyphcache.c \ imagedraw.c \ imagescale.c \ imageunpack.c \ meshdraw.c \ pathfill.c \ pathscan.c \ pathstroke.c \ porterduff.c \ imagesmooth.c include $(BUILD_STATIC_LIBRARY)
0605tonton-test
pdfview/jni/mupdf/draw/Android.mk
Makefile
gpl3
465
#include "fitz.h" #include <libgen.h> #include "android/log.h" char fz_errorbuf[150*20] = {0}; static int fz_errorlen = 0; static int fz_errorclear = 1; static void fz_printerror(int type, const char *file, int line, const char *func, char *msg) { char buf[150]; int len; char *s; s = strrchr(file, '\\'); if (s) file = s + 1; __android_log_print(ANDROID_LOG_INFO, "mupdf", "%c %s:%d: %s(): %s\n", type, basename(file), line, func, msg); snprintf(buf, sizeof buf, "%s:%d: %s(): %s", basename(file), line, func, msg); buf[sizeof(buf)-1] = 0; len = strlen(buf); if (fz_errorclear) { fz_errorclear = 0; fz_errorlen = 0; memset(fz_errorbuf, 0, sizeof fz_errorbuf); } if (fz_errorlen + len + 2 < sizeof fz_errorbuf) { memcpy(fz_errorbuf + fz_errorlen, buf, len); fz_errorlen += len; fz_errorbuf[fz_errorlen++] = '\n'; fz_errorbuf[fz_errorlen] = 0; } } void fz_warn(char *fmt, ...) { va_list ap; fprintf(stderr, "warning: "); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, "\n"); } fz_error fz_throwimp(const char *file, int line, const char *func, char *fmt, ...) { char buf[150]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); buf[sizeof(buf)-1] = 0; fz_printerror('+', file, line, func, buf); return -1; } fz_error fz_rethrowimp(const char *file, int line, const char *func, fz_error cause, char *fmt, ...) { char buf[150]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); buf[sizeof(buf)-1] = 0; fz_printerror('|', file, line, func, buf); return cause; } void fz_catchimp(const char *file, int line, const char *func, fz_error cause, char *fmt, ...) { char buf[150]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); buf[sizeof(buf)-1] = 0; fz_printerror('\\', file, line, func, buf); fz_errorclear = 1; }
0605tonton-test
pdfview/jni/mupdf/fitz/apv_base_error.c
C
gpl3
1,899
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_C_INCLUDES := $(LOCAL_PATH)/../mupdf $(LOCAL_PATH)/../../jpeg $(LOCAL_PATH)/../../pdfview2/include \ $(LOCAL_PATH)/../../jbig2dec $(LOCAL_PATH)/../../openjpeg LOCAL_MODULE := fitz LOCAL_SRC_FILES := \ apv_base_error.c \ base_hash.c \ base_memory.c \ base_string.c \ base_geometry.c \ \ crypt_aes.c \ crypt_arc4.c \ crypt_md5.c \ \ obj_array.c \ obj_dict.c \ obj_print.c \ obj_simple.c \ \ stm_buffer.c \ stm_open.c \ stm_read.c \ \ filt_basic.c \ \ filt_dctd.c \ filt_faxd.c \ filt_flate.c \ filt_lzwd.c \ filt_predict.c \ filt_jbig2d.c \ filt_jpxd.c \ \ res_colorspace.c \ res_font.c \ res_pixmap.c \ res_shade.c \ res_text.c \ res_path.c \ \ dev_list.c \ dev_draw.c \ dev_null.c \ dev_text.c \ dev_bbox.c include $(BUILD_STATIC_LIBRARY) # vim: set sts=8 sw=8 ts=8 noet:
0605tonton-test
pdfview/jni/mupdf/fitz/Android.mk
Makefile
gpl3
877
include $(call all-subdir-makefiles)
0605tonton-test
pdfview/jni/mupdf/Android.mk
Makefile
gpl3
37
LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := openjpeg LOCAL_SRC_FILES := \ bio.c \ cio.c \ dwt.c \ event.c \ image.c \ j2k.c \ j2k_lib.c \ jp2.c \ jpt.c \ mct.c \ mqc.c \ openjpeg.c \ pi.c \ raw.c \ t1.c \ t1_generate_luts.c \ t2.c \ tcd.c \ tgt.c include $(BUILD_STATIC_LIBRARY) # vim: set sts=8 sw=8 ts=8 noet:
0605tonton-test
pdfview/jni/openjpeg/Android.mk
Makefile
gpl3
362
APP_MODULES := mupdf fitz fitzdraw jpeg pdfview2 jbig2dec openjpeg
0605tonton-test
pdfview/jni/Application.mk
Makefile
gpl3
66
#ifdef PDFVIEW2_H__ #error PDFVIEW2_H__ can be included only once #endif #define PDFVIEW2_H__ #include "fitz.h" #include "mupdf.h" /** * Holds pdf info. */ typedef struct { pdf_xref *xref; pdf_outline *outline; int fileno; /* used only when opening by file descriptor */ pdf_page **pages; /* lazy-loaded pages */ fz_glyphcache *drawcache; } pdf_t; /* * Declarations */ pdf_t* create_pdf_t(); pdf_t* parse_pdf_file(const char *filename, int fileno); jint* get_page_image_bitmap(pdf_t *pdf, int pageno, int zoom_pmil, int left, int top, int rotation, int *blen, int *width, int *height); pdf_t* get_pdf_from_this(JNIEnv *env, jobject this); void get_size(JNIEnv *env, jobject size, int *width, int *height); void save_size(JNIEnv *env, jobject size, int width, int height); void fix_samples(unsigned char *bytes, unsigned int w, unsigned int h); int get_page_size(pdf_t *pdf, int pageno, int *width, int *height); void pdf_android_loghandler(const char *m); jobject create_find_result(JNIEnv *env); void set_find_result_page(JNIEnv *env, jobject findResult, int page); void add_find_result_marker(JNIEnv *env, jobject findResult, int x0, int y0, int x1, int y1); void add_find_result_to_list(JNIEnv *env, jobject *list, jobject find_result); int convert_point_pdf_to_apv(pdf_t *pdf, int page, int *x, int *y); int convert_box_pdf_to_apv(pdf_t *pdf, int page, fz_bbox *bbox); int find_next(JNIEnv *env, jobject this, int direction); pdf_page* get_page(pdf_t *pdf, int pageno);
0605tonton-test
pdfview/jni/pdfview2/pdfview2.h
C
gpl3
1,507
#include <string.h> #include <jni.h> #include "android/log.h" #include "pdfview2.h" #define PDFVIEW_LOG_TAG "cx.hell.android.pdfview" #define PDFVIEW_MAX_PAGES_LOADED 16 extern char fz_errorbuf[150*20]; /* defined in fitz/apv_base_error.c */ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) { __android_log_print(ANDROID_LOG_INFO, PDFVIEW_LOG_TAG, "JNI_OnLoad"); fz_accelerate(); /* pdf_setloghandler(pdf_android_loghandler); */ return JNI_VERSION_1_2; } /** * Implementation of native method PDF.parseFile. * Opens file and parses at least some bytes - so it could take a while. * @param file_name file name to parse. */ JNIEXPORT void JNICALL Java_cx_hell_android_pdfview_PDF_parseFile( JNIEnv *env, jobject jthis, jstring file_name) { const char *c_file_name = NULL; jboolean iscopy; jclass this_class; jfieldID pdf_field_id; pdf_t *pdf = NULL; c_file_name = (*env)->GetStringUTFChars(env, file_name, &iscopy); this_class = (*env)->GetObjectClass(env, jthis); pdf_field_id = (*env)->GetFieldID(env, this_class, "pdf_ptr", "I"); pdf = parse_pdf_file(c_file_name, 0); (*env)->ReleaseStringUTFChars(env, file_name, c_file_name); (*env)->SetIntField(env, jthis, pdf_field_id, (int)pdf); } /** * Create pdf_t struct from opened file descriptor. */ JNIEXPORT void JNICALL Java_cx_hell_android_pdfview_PDF_parseFileDescriptor( JNIEnv *env, jobject jthis, jobject fileDescriptor) { int fileno; jclass this_class; jfieldID pdf_field_id; pdf_t *pdf = NULL; this_class = (*env)->GetObjectClass(env, jthis); pdf_field_id = (*env)->GetFieldID(env, this_class, "pdf_ptr", "I"); fileno = get_descriptor_from_file_descriptor(env, fileDescriptor); pdf = parse_pdf_file(NULL, fileno); (*env)->SetIntField(env, jthis, pdf_field_id, (int)pdf); } /** * Implementation of native method PDF.getPageCount - return page count of this PDF file. * Returns -1 on error, eg if pdf_ptr is NULL. * @param env JNI Environment * @param this PDF object * @return page count or -1 on error */ JNIEXPORT jint JNICALL Java_cx_hell_android_pdfview_PDF_getPageCount( JNIEnv *env, jobject this) { pdf_t *pdf = NULL; pdf = get_pdf_from_this(env, this); if (pdf == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "pdf is null"); return -1; } return pdf_getpagecount(pdf->xref); } JNIEXPORT jintArray JNICALL Java_cx_hell_android_pdfview_PDF_renderPage( JNIEnv *env, jobject this, jint pageno, jint zoom, jint left, jint top, jint rotation, jobject size) { int blen; jint *buf; /* rendered page, freed before return, as bitmap */ jintArray jints; /* return value */ int *jbuf; /* pointer to internal jint */ pdf_t *pdf; /* parsed pdf data, extracted from java's "this" object */ int width, height; get_size(env, size, &width, &height); __android_log_print(ANDROID_LOG_DEBUG, "cx.hell.android.pdfview", "jni renderPage(pageno: %d, zoom: %d, left: %d, right: %d, width: %d, height: %d) start", (int)pageno, (int)zoom, (int)left, (int)top, (int)width, (int)height); pdf = get_pdf_from_this(env, this); buf = get_page_image_bitmap(pdf, pageno, zoom, left, top, rotation, &blen, &width, &height); if (buf == NULL) return NULL; save_size(env, size, width, height); /* TODO: learn jni and avoid copying bytes ;) */ jints = (*env)->NewIntArray(env, blen); jbuf = (*env)->GetIntArrayElements(env, jints, NULL); memcpy(jbuf, buf, blen); (*env)->ReleaseIntArrayElements(env, jints, jbuf, 0); free(buf); return jints; } JNIEXPORT jint JNICALL Java_cx_hell_android_pdfview_PDF_getPageSize( JNIEnv *env, jobject this, jint pageno, jobject size) { int width, height, error; pdf_t *pdf; pdf = get_pdf_from_this(env, this); if (pdf == NULL) { __android_log_print(ANDROID_LOG_ERROR, "cx.hell.android.pdfview", "this.pdf is null"); return 1; } error = get_page_size(pdf, pageno, &width, &height); if (error != 0) { __android_log_print(ANDROID_LOG_ERROR, "cx.hell.android.pdfview", "get_page_size error: %d", (int)error); __android_log_print(ANDROID_LOG_ERROR, "cx.hell.android.pdfview", "fitz error is:\n%s", fz_errorbuf); return 2; } save_size(env, size, width, height); return 0; } /** * Free resources allocated in native code. */ JNIEXPORT void JNICALL Java_cx_hell_android_pdfview_PDF_freeMemory( JNIEnv *env, jobject this) { pdf_t *pdf = NULL; jclass this_class = (*env)->GetObjectClass(env, this); jfieldID pdf_field_id = (*env)->GetFieldID(env, this_class, "pdf_ptr", "I"); __android_log_print(ANDROID_LOG_DEBUG, "cx.hell.android.pdfview", "jni freeMemory()"); pdf = (pdf_t*) (*env)->GetIntField(env, this, pdf_field_id); (*env)->SetIntField(env, this, pdf_field_id, 0); /* if (pdf->pages) { int i; int pagecount; pagecount = pdf_getpagecount(pdf->xref); for(i = 0; i < pagecount; ++i) { if (pdf->pages[i]) { pdf_droppage(pdf->pages[i]); } } free(pdf->pages); pdf->pages = NULL; } */ /* if (pdf->textlines) { int i; int pagecount; pagecount = pdf_getpagecount(pdf->xref); for(i = 0; i < pagecount; ++i) { if (pdf->textlines[i]) { pdf_droptextline(pdf->textlines[i]); } } free(pdf->textlines); pdf->textlines = NULL; } */ if (pdf->drawcache) { fz_freeglyphcache(pdf->drawcache); pdf->drawcache = NULL; } /* pdf->fileno is dup()-ed in parse_pdf_fileno */ if (pdf->fileno >= 0) close(pdf->fileno); free(pdf); } JNIEXPORT jobject JNICALL Java_cx_hell_android_pdfview_PDF_find( JNIEnv *env, jobject this, jstring text, jint pageno) { pdf_t *pdf = NULL; char *ctext = NULL; jboolean is_copy; jobject results = NULL; pdf_page *page = NULL; fz_textspan *textspan = NULL, *ln = NULL; fz_device *dev = NULL; char *textlinechars; char *found = NULL; fz_error error = 0; jobject find_result = NULL; ctext = (char*)(*env)->GetStringUTFChars(env, text, &is_copy); if (ctext == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "text cannot be null"); (*env)->ReleaseStringUTFChars(env, text, ctext); return NULL; } __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "find(%s)", ctext); pdf = get_pdf_from_this(env, this); page = get_page(pdf, pageno); textspan = fz_newtextspan(); dev = fz_newtextdevice(textspan); error = pdf_runpage(pdf->xref, page, dev, fz_identity); if (error) { /* TODO: cleanup */ fz_rethrow(error, "text extraction failed"); return NULL; } for(ln = textspan; ln; ln = ln->next) { textlinechars = (char*)malloc(ln->len + 1); { int i; for(i = 0; i < ln->len; ++i) textlinechars[i] = ln->text[i].c; } textlinechars[ln->len] = 0; found = strcasestr(textlinechars, ctext); if (found) { __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "found something, creating empty find result"); find_result = create_find_result(env); if (find_result == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "tried to create empty find result, but got NULL instead"); /* TODO: free resources */ (*env)->ReleaseStringUTFChars(env, text, ctext); return; } __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "found something, empty find result created"); set_find_result_page(env, find_result, pageno); /* now add markers to this find result */ { int i = 0; int i0, i1; /* int x, y; */ fz_bbox charbox; i0 = (found-textlinechars); i1 = i0 + strlen(ctext); for(i = i0; i < i1; ++i) { __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "adding marker for letter %d: %c", i, textlinechars[i]); /* x = ln->text[i].x; y = ln->text[i].y; convert_point_pdf_to_apv(pdf, pageno, &x, &y); */ charbox = ln->text[i].bbox; convert_box_pdf_to_apv(pdf, pageno, &charbox); /* add_find_result_marker(env, find_result, x-2, y-2, x+2, y+2); */ add_find_result_marker(env, find_result, charbox.x0-2, charbox.y0-2, charbox.x1+2, charbox.y1+2); /* TODO: check errors */ } /* TODO: obviously this sucks massively, good God please forgive me for writing this; if only I had more time... */ /* x = ((float)(ln->text[i1-1].x - ln->text[i0].x)) / (float)strlen(ctext) + ln->text[i1-1].x; y = ((float)(ln->text[i1-1].y - ln->text[i0].y)) / (float)strlen(ctext) + ln->text[i1-1].y; convert_point_pdf_to_apv(pdf, pageno, &x, &y); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "adding final marker"); add_find_result_marker(env, find_result, x-2, y-2, x+2, y+2 ); */ } __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "adding find result to list"); add_find_result_to_list(env, &results, find_result); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "added find result to list"); } free(textlinechars); } fz_freedevice(dev); fz_freetextspan(textspan); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "releasing text back to jvm"); (*env)->ReleaseStringUTFChars(env, text, ctext); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "returning results"); return results; } /** * Create empty FindResult object. * @param env JNI Environment * @return newly created, empty FindResult object */ jobject create_find_result(JNIEnv *env) { static jmethodID constructorID; jclass findResultClass = NULL; static int jni_ids_cached = 0; jobject findResultObject = NULL; findResultClass = (*env)->FindClass(env, "cx/hell/android/lib/pagesview/FindResult"); if (findResultClass == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "create_find_result: FindClass returned NULL"); return NULL; } if (jni_ids_cached == 0) { constructorID = (*env)->GetMethodID(env, findResultClass, "<init>", "()V"); if (constructorID == NULL) { (*env)->DeleteLocalRef(env, findResultClass); __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "create_find_result: couldn't get method id for FindResult constructor"); return NULL; } jni_ids_cached = 1; } findResultObject = (*env)->NewObject(env, findResultClass, constructorID); return findResultObject; } void add_find_result_to_list(JNIEnv *env, jobject *list, jobject find_result) { static int jni_ids_cached = 0; static jmethodID list_add_method_id = NULL; jclass list_class = NULL; if (list == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "list cannot be null - it must be a pointer jobject variable"); return; } if (find_result == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "find_result cannot be null"); return; } if (*list == NULL) { jmethodID list_constructor_id; __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "creating ArrayList"); list_class = (*env)->FindClass(env, "java/util/ArrayList"); if (list_class == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "couldn't find class java/util/ArrayList"); return; } list_constructor_id = (*env)->GetMethodID(env, list_class, "<init>", "()V"); if (!list_constructor_id) { __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "couldn't find ArrayList constructor"); return; } *list = (*env)->NewObject(env, list_class, list_constructor_id); if (*list == NULL) { __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "failed to create ArrayList: NewObject returned NULL"); return; } } if (!jni_ids_cached) { if (list_class == NULL) { list_class = (*env)->FindClass(env, "java/util/ArrayList"); if (list_class == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "couldn't find class java/util/ArrayList"); return; } } list_add_method_id = (*env)->GetMethodID(env, list_class, "add", "(Ljava/lang/Object;)Z"); if (list_add_method_id == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "couldn't get ArrayList.add method id"); return; } jni_ids_cached = 1; } __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "calling ArrayList.add"); (*env)->CallBooleanMethod(env, *list, list_add_method_id, find_result); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "add_find_result_to_list done"); } /** * Set find results page member. * @param JNI environment * @param findResult find result object that should be modified * @param page new value for page field */ void set_find_result_page(JNIEnv *env, jobject findResult, int page) { static char jni_ids_cached = 0; static jfieldID page_field_id = 0; __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "trying to set find results page number"); if (jni_ids_cached == 0) { jclass findResultClass = (*env)->GetObjectClass(env, findResult); page_field_id = (*env)->GetFieldID(env, findResultClass, "page", "I"); jni_ids_cached = 1; } (*env)->SetIntField(env, findResult, page_field_id, page); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "find result page number set"); } /** * Add marker to find result. */ void add_find_result_marker(JNIEnv *env, jobject findResult, int x0, int y0, int x1, int y1) { static jmethodID addMarker_methodID = 0; static unsigned char jni_ids_cached = 0; if (!jni_ids_cached) { jclass findResultClass = NULL; findResultClass = (*env)->FindClass(env, "cx/hell/android/lib/pagesview/FindResult"); if (findResultClass == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "add_find_result_marker: FindClass returned NULL"); return; } addMarker_methodID = (*env)->GetMethodID(env, findResultClass, "addMarker", "(IIII)V"); if (addMarker_methodID == NULL) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "add_find_result_marker: couldn't find FindResult.addMarker method ID"); return; } jni_ids_cached = 1; } (*env)->CallVoidMethod(env, findResult, addMarker_methodID, x0, y0, x1, y1); /* TODO: is always really int jint? */ } /** * Get pdf_ptr field value, cache field address as a static field. * @param env Java JNI Environment * @param this object to get "pdf_ptr" field from * @return pdf_ptr field value */ pdf_t* get_pdf_from_this(JNIEnv *env, jobject this) { static jfieldID field_id = 0; static unsigned char field_is_cached = 0; pdf_t *pdf = NULL; if (! field_is_cached) { jclass this_class = (*env)->GetObjectClass(env, this); field_id = (*env)->GetFieldID(env, this_class, "pdf_ptr", "I"); field_is_cached = 1; __android_log_print(ANDROID_LOG_DEBUG, "cx.hell.android.pdfview", "cached pdf_ptr field id %d", (int)field_id); } pdf = (pdf_t*) (*env)->GetIntField(env, this, field_id); return pdf; } /** * Get descriptor field value from FileDescriptor class, cache field offset. * This is undocumented private field. * @param env JNI Environment * @param this FileDescriptor object * @return file descriptor field value */ int get_descriptor_from_file_descriptor(JNIEnv *env, jobject this) { static jfieldID field_id = 0; static unsigned char is_cached = 0; if (!is_cached) { jclass this_class = (*env)->GetObjectClass(env, this); field_id = (*env)->GetFieldID(env, this_class, "descriptor", "I"); is_cached = 1; __android_log_print(ANDROID_LOG_DEBUG, "cx.hell.android.pdfview", "cached descriptor field id %d", (int)field_id); } __android_log_print(ANDROID_LOG_DEBUG, "cx.hell.android.pdfview", "will get descriptor field..."); return (*env)->GetIntField(env, this, field_id); } void get_size(JNIEnv *env, jobject size, int *width, int *height) { static jfieldID width_field_id = 0; static jfieldID height_field_id = 0; static unsigned char fields_are_cached = 0; if (! fields_are_cached) { jclass size_class = (*env)->GetObjectClass(env, size); width_field_id = (*env)->GetFieldID(env, size_class, "width", "I"); height_field_id = (*env)->GetFieldID(env, size_class, "height", "I"); fields_are_cached = 1; __android_log_print(ANDROID_LOG_DEBUG, "cx.hell.android.pdfview", "cached Size fields"); } *width = (*env)->GetIntField(env, size, width_field_id); *height = (*env)->GetIntField(env, size, height_field_id); } /** * Store width and height values into PDF.Size object, cache field ids in static members. * @param env JNI Environment * @param width width to store * @param height height field value to be stored * @param size target PDF.Size object */ void save_size(JNIEnv *env, jobject size, int width, int height) { static jfieldID width_field_id = 0; static jfieldID height_field_id = 0; static unsigned char fields_are_cached = 0; if (! fields_are_cached) { jclass size_class = (*env)->GetObjectClass(env, size); width_field_id = (*env)->GetFieldID(env, size_class, "width", "I"); height_field_id = (*env)->GetFieldID(env, size_class, "height", "I"); fields_are_cached = 1; __android_log_print(ANDROID_LOG_DEBUG, "cx.hell.android.pdfview", "cached Size fields"); } (*env)->SetIntField(env, size, width_field_id, width); (*env)->SetIntField(env, size, height_field_id, height); } /** * pdf_t "constructor": create empty pdf_t with default values. * @return newly allocated pdf_t struct with fields set to default values */ pdf_t* create_pdf_t() { pdf_t *pdf = NULL; pdf = (pdf_t*)malloc(sizeof(pdf_t)); pdf->xref = NULL; pdf->outline = NULL; pdf->fileno = -1; pdf->pages = NULL; pdf->drawcache = NULL; } #if 0 /** * Parse bytes into PDF struct. * @param bytes pointer to bytes that should be parsed * @param len length of byte buffer * @return initialized pdf_t struct; or NULL if loading failed */ pdf_t* parse_pdf_bytes(unsigned char *bytes, size_t len) { pdf_t *pdf; fz_error error; pdf = create_pdf_t(); pdf->xref = pdf_newxref(); error = pdf_loadxref_mem(pdf->xref, bytes, len); if (error) { __android_log_print(ANDROID_LOG_ERROR, "cx.hell.android.pdfview", "got err from pdf_loadxref_mem: %d", (int)error); __android_log_print(ANDROID_LOG_ERROR, "cx.hell.android.pdfview", "fz errors:\n%s", fz_errorbuf); /* TODO: free resources */ return NULL; } error = pdf_decryptxref(pdf->xref); if (error) { return NULL; } if (pdf_needspassword(pdf->xref)) { int authenticated = 0; authenticated = pdf_authenticatepassword(pdf->xref, ""); if (!authenticated) { /* TODO: ask for password */ __android_log_print(ANDROID_LOG_ERROR, "cx.hell.android.pdfview", "failed to authenticate with empty password"); return NULL; } } pdf->xref->root = fz_resolveindirect(fz_dictgets(pdf->xref->trailer, "Root")); fz_keepobj(pdf->xref->root); pdf->xref->info = fz_resolveindirect(fz_dictgets(pdf->xref->trailer, "Info")); fz_keepobj(pdf->xref->info); pdf->outline = pdf_loadoutline(pdf->xref); return pdf; } #endif /** * Parse file into PDF struct. * Use filename if it's not null, otherwise use fileno. */ pdf_t* parse_pdf_file(const char *filename, int fileno) { pdf_t *pdf; fz_error error; int fd; fz_stream *file; __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "parse_pdf_file(%s, %d)", filename, fileno); pdf = create_pdf_t(); if (filename) { fd = open(filename, O_BINARY | O_RDONLY, 0666); if (fd < 0) { return NULL; } } else { pdf->fileno = dup(fileno); fd = pdf->fileno; } file = fz_openfile(fd); error = pdf_openxrefwithstream(&(pdf->xref), file, NULL); if (!pdf->xref) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "got NULL from pdf_openxref"); __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "fz errors:\n%s", fz_errorbuf); return NULL; } /* error = pdf_decryptxref(pdf->xref); if (error) { return NULL; } */ if (pdf_needspassword(pdf->xref)) { int authenticated = 0; authenticated = pdf_authenticatepassword(pdf->xref, ""); if (!authenticated) { /* TODO: ask for password */ __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "failed to authenticate with empty password"); return NULL; } } /* pdf->xref->root = fz_resolveindirect(fz_dictgets(pdf->xref->trailer, "Root")); fz_keepobj(pdf->xref->root); pdf->xref->info = fz_resolveindirect(fz_dictgets(pdf->xref->trailer, "Info")); if (pdf->xref->info) fz_keepobj(pdf->xref->info); */ pdf->outline = pdf_loadoutline(pdf->xref); error = pdf_loadpagetree(pdf->xref); if (error) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "pdf_loadpagetree failed: %d", error); /* TODO: clean resources */ return NULL; } { int c = 0; c = pdf_getpagecount(pdf->xref); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "page count: %d", c); } return pdf; } /** * Calculate zoom to best match given dimensions. * There's no guarantee that page zoomed by resulting zoom will fit rectangle max_width x max_height exactly. * @param max_width expected max width * @param max_height expected max height * @param page original page * @return zoom required to best fit page into max_width x max_height rectangle */ double get_page_zoom(pdf_page *page, int max_width, int max_height) { double page_width, page_height; double zoom_x, zoom_y; double zoom; page_width = page->mediabox.x1 - page->mediabox.x0; page_height = page->mediabox.y1 - page->mediabox.y0; zoom_x = max_width / page_width; zoom_y = max_height / page_height; zoom = (zoom_x < zoom_y) ? zoom_x : zoom_y; return zoom; } /** * Lazy get-or-load page. * Only PDFVIEW_MAX_PAGES_LOADED pages can be loaded at the time. * @param pdf pdf struct * @param pageno 0-based page number * @return pdf_page */ pdf_page* get_page(pdf_t *pdf, int pageno) { fz_error error = 0; int loaded_pages = 0; int pagecount; pagecount = pdf_getpagecount(pdf->xref); if (!pdf->pages) { int i; pdf->pages = (pdf_page**)malloc(pagecount * sizeof(pdf_page*)); for(i = 0; i < pagecount; ++i) pdf->pages[i] = NULL; } if (!pdf->pages[pageno]) { pdf_page *page = NULL; fz_obj *obj = NULL; int loaded_pages = 0; int i = 0; for(i = 0; i < pagecount; ++i) { if (pdf->pages[i]) loaded_pages++; } #if 0 if (loaded_pages >= PDFVIEW_MAX_PAGES_LOADED) { int page_to_drop = 0; /* not the page number */ int j = 0; __android_log_print(ANDROID_LOG_INFO, PDFVIEW_LOG_TAG, "already loaded %d pages, going to drop random one", loaded_pages); page_to_drop = rand() % loaded_pages; __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "will drop %d-th loaded page", page_to_drop); /* search for page_to_drop-th loaded page and then drop it */ for(i = 0; i < pagecount; ++i) { if (pdf->pages[i]) { /* one of loaded pages, the j-th one */ if (j == page_to_drop) { __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "found %d-th loaded page, it's %d-th in document, dropping now", page_to_drop, i); pdf_droppage(pdf->pages[i]); pdf->pages[i] = NULL; break; } else { j++; } } } } #endif obj = pdf_getpageobject(pdf->xref, pageno+1); error = pdf_loadpage(&page, pdf->xref, obj); if (error) { __android_log_print(ANDROID_LOG_ERROR, "cx.hell.android.pdfview", "pdf_loadpage -> %d", (int)error); __android_log_print(ANDROID_LOG_ERROR, "cx.hell.android.pdfview", "fitz error is:\n%s", fz_errorbuf); return NULL; } pdf->pages[pageno] = page; } return pdf->pages[pageno]; } /** * Get part of page as bitmap. * Parameters left, top, width and height are interprted after scalling, so if we have 100x200 page scalled by 25% and * request 0x0 x 25x50 tile, we should get 25x50 bitmap of whole page content. * Page size is currently MediaBox size: http://www.prepressure.com/pdf/basics/page_boxes, but probably shuld be TrimBox. * pageno is 0-based. */ jint* get_page_image_bitmap(pdf_t *pdf, int pageno, int zoom_pmil, int left, int top, int rotation, int *blen, int *width, int *height) { unsigned char *bytes = NULL; fz_matrix ctm; double zoom; fz_rect bbox; fz_error error = 0; pdf_page *page = NULL; fz_pixmap *image = NULL; static int runs = 0; fz_device *dev = NULL; zoom = (double)zoom_pmil / 1000.0; __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "get_page_image_bitmap(pageno: %d) start", (int)pageno); if (!pdf->drawcache) { pdf->drawcache = fz_newglyphcache(); if (!pdf->drawcache) { __android_log_print(ANDROID_LOG_ERROR, PDFVIEW_LOG_TAG, "failed to create glyphcache"); return NULL; } } /* pdf_flushxref(pdf->xref, 0); */ page = get_page(pdf, pageno); if (!page) return NULL; /* TODO: handle/propagate errors */ ctm = fz_identity; ctm = fz_concat(ctm, fz_translate(-page->mediabox.x0, -page->mediabox.y1)); ctm = fz_concat(ctm, fz_scale(zoom, -zoom)); rotation = page->rotate + rotation * -90; if (rotation != 0) ctm = fz_concat(ctm, fz_rotate(rotation)); bbox = fz_transformrect(ctm, page->mediabox); /* not bbox holds page after transform, but we only need tile at (left,right) from top-left corner */ bbox.x0 = bbox.x0 + left; bbox.y0 = bbox.y0 + top; bbox.x1 = bbox.x0 + *width; bbox.y1 = bbox.y0 + *height; #if 0 error = fz_rendertree(&image, pdf->renderer, page->tree, ctm, fz_roundrect(bbox), 1); if (error) { fz_rethrow(error, "rendering failed"); /* TODO: cleanup mem on error, so user can try to open many files without causing memleaks; also report errors nicely to user */ return NULL; } #endif image = fz_newpixmap(fz_devicergb, bbox.x0, bbox.y0, *width, *height); fz_clearpixmap(image, 0xff); memset(image->samples, 0xff, image->h * image->w * image->n); dev = fz_newdrawdevice(pdf->drawcache, image); error = pdf_runpage(pdf->xref, page, dev, ctm); if (error) { /* TODO: cleanup */ fz_rethrow(error, "rendering failed"); return NULL; } fz_freedevice(dev); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "got image %d x %d, asked for %d x %d", (int)(image->w), (int)(image->h), *width, *height); fix_samples(image->samples, image->w, image->h); /* TODO: shouldn't malloc so often; but in practice, those temp malloc-memcpy pairs don't cost that much */ bytes = (unsigned char*)malloc(image->w * image->h * 4); memcpy(bytes, image->samples, image->w * image->h * 4); *blen = image->w * image->h * 4; *width = image->w; *height = image->h; fz_droppixmap(image); runs += 1; return (jint*)bytes; } /** * Reorder bytes in image data - convert from mupdf image to android image. * TODO: make it portable across different architectures (when they're released). * TODO: make mupdf write pixels in correct format */ void fix_samples(unsigned char *bytes, unsigned int w, unsigned int h) { unsigned char r,g,b,a; unsigned i = 0; for (i = 0; i < (w*h); ++i) { unsigned int o = i*4; /* a = bytes[o+0]; r = bytes[o+1]; g = bytes[o+2]; b = bytes[o+3]; */ r = bytes[o+0]; g = bytes[o+1]; b = bytes[o+2]; a = bytes[o+3]; bytes[o+0] = b; /* b */ bytes[o+1] = g; /* g */ bytes[o+2] = r; /* r */ bytes[o+3] = a; } } /** * Get page size in APV's convention. * @param page 0-based page number * @param pdf pdf struct * @param width target for width value * @param height target for height value * @return error code - 0 means ok */ int get_page_size(pdf_t *pdf, int pageno, int *width, int *height) { fz_error error = 0; fz_obj *pageobj = NULL; fz_obj *sizeobj = NULL; fz_rect bbox; fz_obj *rotateobj = NULL; int rotate = 0; pageobj = pdf_getpageobject(pdf->xref, pageno+1); sizeobj = fz_dictgets(pageobj, "MediaBox"); rotateobj = fz_dictgets(pageobj, "Rotate"); if (fz_isint(rotateobj)) { rotate = fz_toint(rotateobj); } else { rotate = 0; } bbox = pdf_torect(sizeobj); if (rotate != 0 && (rotate % 180) == 90) { *width = bbox.y1 - bbox.y0; *height = bbox.x1 - bbox.x0; } else { *width = bbox.x1 - bbox.x0; *height = bbox.y1 - bbox.y0; } return 0; } #if 0 /** * Convert coordinates from pdf to APVs. * TODO: faster? lazy? * @return error code, 0 means ok */ int convert_point_pdf_to_apv(pdf_t *pdf, int page, int *x, int *y) { fz_error error = 0; fz_obj *pageobj = NULL; fz_obj *rotateobj = NULL; fz_obj *sizeobj = NULL; fz_rect bbox; int rotate = 0; fz_point p; __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "convert_point_pdf_to_apv()"); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "trying to convert %d x %d to APV coords", *x, *y); pageobj = pdf_getpageobject(pdf->xref, page+1); if (!pageobj) return -1; sizeobj = fz_dictgets(pageobj, "MediaBox"); if (!sizeobj) return -1; bbox = pdf_torect(sizeobj); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "page bbox is %.1f, %.1f, %.1f, %.1f", bbox.x0, bbox.y0, bbox.x1, bbox.y1); rotateobj = fz_dictgets(pageobj, "Rotate"); if (fz_isint(rotateobj)) { rotate = fz_toint(rotateobj); } else { rotate = 0; } __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "rotate is %d", (int)rotate); p.x = *x; p.y = *y; if (rotate != 0) { fz_matrix m; m = fz_rotate(-rotate); bbox = fz_transformrect(m, bbox); p = fz_transformpoint(m, p); } __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "after rotate bbox is: %.1f, %.1f, %.1f, %.1f", bbox.x0, bbox.y0, bbox.x1, bbox.y1); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "after rotate point is: %.1f, %.1f", p.x, p.y); *x = p.x - MIN(bbox.x0,bbox.x1); *y = MAX(bbox.y1, bbox.y0) - p.y; __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "result is: %d, %d", *x, *y); return 0; } #endif /** * Convert coordinates from pdf to APV. * Result is stored in location pointed to by bbox param. * This function has to get page MediaBox relative to which bbox is located. * This function should not allocate any memory. * @return error code, 0 means ok */ int convert_box_pdf_to_apv(pdf_t *pdf, int page, fz_bbox *bbox) { fz_error error = 0; fz_obj *pageobj = NULL; fz_obj *rotateobj = NULL; fz_obj *sizeobj = NULL; fz_rect page_bbox; fz_rect param_bbox; int rotate = 0; float height = 0; float width = 0; __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "convert_box_pdf_to_apv(page: %d, bbox: %d %d %d %d)", page, bbox->x0, bbox->y0, bbox->x1, bbox->y1); /* copying field by field becuse param_bbox is fz_rect (floats) and *bbox is fz_bbox (ints) */ param_bbox.x0 = bbox->x0; param_bbox.y0 = bbox->y0; param_bbox.x1 = bbox->x1; param_bbox.y1 = bbox->y1; pageobj = pdf_getpageobject(pdf->xref, page+1); if (!pageobj) return -1; sizeobj = fz_dictgets(pageobj, "MediaBox"); if (!sizeobj) return -1; page_bbox = pdf_torect(sizeobj); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "page bbox is %.1f, %.1f, %.1f, %.1f", page_bbox.x0, page_bbox.y0, page_bbox.x1, page_bbox.y1); rotateobj = fz_dictgets(pageobj, "Rotate"); if (fz_isint(rotateobj)) { rotate = fz_toint(rotateobj); } else { rotate = 0; } __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "rotate is %d", (int)rotate); if (rotate != 0) { fz_matrix m; m = fz_rotate(-rotate); param_bbox = fz_transformrect(m, param_bbox); page_bbox = fz_transformrect(m, page_bbox); } __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "after rotate page bbox is: %.1f, %.1f, %.1f, %.1f", page_bbox.x0, page_bbox.y0, page_bbox.x1, page_bbox.y1); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "after rotate param bbox is: %.1f, %.1f, %.1f, %.1f", param_bbox.x0, param_bbox.y0, param_bbox.x1, param_bbox.y1); /* set result: param bounding box relative to left-top corner of page bounding box */ /* bbox->x0 = MIN(param_bbox.x0, param_bbox.x1) - MIN(page_bbox.x0, page_bbox.x1); bbox->y0 = MIN(param_bbox.y0, param_bbox.y1) - MIN(page_bbox.y0, page_bbox.y1); bbox->x1 = MAX(param_bbox.x0, param_bbox.x1) - MIN(page_bbox.x0, page_bbox.x1); bbox->y1 = MAX(param_bbox.y0, param_bbox.y1) - MIN(page_bbox.y0, page_bbox.y1); */ width = ABS(page_bbox.x0 - page_bbox.x1); height = ABS(page_bbox.y0 - page_bbox.y1); bbox->x0 = (MIN(param_bbox.x0, param_bbox.x1) - MIN(page_bbox.x0, page_bbox.x1)); bbox->y1 = height - (MIN(param_bbox.y0, param_bbox.y1) - MIN(page_bbox.y0, page_bbox.y1)); bbox->x1 = (MAX(param_bbox.x0, param_bbox.x1) - MIN(page_bbox.x0, page_bbox.x1)); bbox->y0 = height - (MAX(param_bbox.y0, param_bbox.y1) - MIN(page_bbox.y0, page_bbox.y1)); __android_log_print(ANDROID_LOG_DEBUG, PDFVIEW_LOG_TAG, "result after transformations: %d, %d, %d, %d", bbox->x0, bbox->y0, bbox->x1, bbox->y1); return 0; } void pdf_android_loghandler(const char *m) { __android_log_print(ANDROID_LOG_DEBUG, "cx.hell.android.pdfview.mupdf", m); } /* vim: set sts=4 ts=4 sw=4 et: */
0605tonton-test
pdfview/jni/pdfview2/pdfview2.c
C
gpl3
36,144
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_C_INCLUDES := $(LOCAL_PATH)/../mupdf/fitz $(LOCAL_PATH)/../mupdf/mupdf $(LOCAL_PATH)/include LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -lz -llog -L$(LOCAL_PATH)/lib -lfreetype #out/apps/pdfview2/libpng.a LOCAL_STATIC_LIBRARIES := mupdf fitz mupdf fitzdraw jpeg jbig2dec openjpeg LOCAL_MODULE := pdfview2 LOCAL_SRC_FILES := pdfview2.c include $(BUILD_SHARED_LIBRARY)
0605tonton-test
pdfview/jni/pdfview2/Android.mk
Makefile
gpl3
425
LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := jpeg LOCAL_SRC_FILES := jaricom.c jcapimin.c jcapistd.c jcarith.c jccoefct.c jccolor.c \ jcdctmgr.c jchuff.c jcinit.c jcmainct.c jcmarker.c jcmaster.c \ jcomapi.c jcparam.c jcprepct.c jcsample.c jctrans.c jdapimin.c \ jdapistd.c jdarith.c jdatadst.c jdatasrc.c jdcoefct.c jdcolor.c \ jddctmgr.c jdhuff.c jdinput.c jdmainct.c jdmarker.c jdmaster.c \ jdmerge.c jdpostct.c jdsample.c jdtrans.c jerror.c jfdctflt.c \ jfdctfst.c jfdctint.c jidctflt.c jidctfst.c jidctint.c jquant1.c \ jquant2.c jutils.c jmemmgr.c \ jmemnobs.c include $(BUILD_STATIC_LIBRARY)
0605tonton-test
pdfview/jni/jpeg/Android.mk
Makefile
gpl3
684
# # Makefile # # Author: Lasse Collin <lasse.collin@tukaani.org> # # This file has been put into the public domain. # You can do whatever you want with this file. # CC = gcc -std=gnu89 BCJ_CPPFLAGS = -DXZ_DEC_X86 -DXZ_DEC_POWERPC -DXZ_DEC_IA64 \ -DXZ_DEC_ARM -DXZ_DEC_ARMTHUMB -DXZ_DEC_SPARC CFLAGS = -ggdb3 -O2 -pedantic -Wall -Wextra RM = rm -f VPATH = ../linux/include/linux ../linux/lib/xz COMMON_SRCS = xz_crc32.c xz_dec_stream.c xz_dec_lzma2.c xz_dec_bcj.c COMMON_OBJS = $(COMMON_SRCS:.c=.o) XZMINIDEC_OBJS = xzminidec.o BUFTEST_OBJS = buftest.o BOOTTEST_OBJS = boottest.o XZ_HEADERS = xz.h xz_private.h xz_stream.h xz_lzma2.h xz_config.h PROGRAMS = xzminidec buftest boottest ALL_CPPFLAGS = -I../linux/include/linux -I. $(BCJ_CPPFLAGS) $(CPPFLAGS) all: $(PROGRAMS) %.o: %.c $(XZ_HEADERS) $(CC) $(ALL_CPPFLAGS) $(CFLAGS) -c -o $@ $< xzminidec: $(COMMON_OBJS) $(XZMINIDEC_OBJS) $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(COMMON_OBJS) $(XZMINIDEC_OBJS) buftest: $(COMMON_OBJS) $(BUFTEST_OBJS) $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(COMMON_OBJS) $(BUFTEST_OBJS) boottest: $(BOOTTEST_OBJS) $(COMMON_SRCS) $(CC) $(ALL_CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $(BOOTTEST_OBJS) .PHONY: clean clean: -$(RM) $(COMMON_OBJS) $(XZMINIDEC_OBJS) $(BUFTEST_OBJS) \ $(BOOTTEST_OBJS) $(PROGRAMS)
0605tonton-test
pdfview/jni/xzx/Makefile
Makefile
gpl3
1,286
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_LDLIBS := -llog LOCAL_MODULE := xzx LOCAL_SRC_FILES := jnixz.c xz_crc32.c xz_dec_stream.c xz_dec_lzma2.c xz_dec_bcj.c LOCAL_CFLAGS := -DXZ_DEC_X86 -DXZ_DEC_POWERPC -DXZ_DEC_IA64 -DXZ_DEC_ARM -DXZ_DEC_ARMTHUMB -DXZ_DEC_SPARC include $(BUILD_SHARED_LIBRARY)
0605tonton-test
pdfview/jni/xzx/Android.mk
Makefile
gpl3
317
/* config.h.in. Generated from configure.ac by autoheader. */ /* Define if building universal (internal helper macro) */ #undef AC_APPLE_UNIVERSAL_BUILD /* Define to 1 if you have the <dlfcn.h> header file. */ #define HAVE_DLFCN_H /* Define if the local libc includes getopt_long() */ #define HAVE_GETOPT_LONG /* Define to 1 if you have the <inttypes.h> header file. */ #define HAVE_INTTYPES_H /* Define to 1 if you have the <libintl.h> header file. */ #undef HAVE_LIBINTL_H /* Define if libpng is available (-lpng) */ #undef HAVE_LIBPNG /* Define to 1 if you have the <memory.h> header file. */ #define HAVE_MEMORY_H /* Define to 1 if you have the `memset' function. */ #define HAVE_MEMSET /* Define to 1 if you have the `snprintf' function. */ #define HAVE_SNPRINTF /* Define to 1 if you have the <stddef.h> header file. */ #define HAVE_STDDEF_H /* Define to 1 if you have the <stdint.h> header file. */ #define HAVE_STDINT_H /* Define to 1 if you have the <stdlib.h> header file. */ #define HAVE_STDLIB_H /* Define to 1 if you have the `strdup' function. */ #define HAVE_STRDUP /* Define to 1 if you have the <strings.h> header file. */ #define HAVE_STRINGS_H /* Define to 1 if you have the <string.h> header file. */ #define HAVE_STRING_H /* Define to 1 if you have the <sys/stat.h> header file. */ #define HAVE_SYS_STAT_H /* Define to 1 if you have the <sys/types.h> header file. */ #define HAVE_SYS_TYPES_H /* Define to 1 if you have the <unistd.h> header file. */ #define HAVE_UNISTD_H /* set by configure if an alternate header with the stdint.h types is found */ #undef JBIG2_REPLACE_STDINT_H /* Define to the sub-directory in which libtool stores uninstalled libraries. */ #undef LT_OBJDIR /* Define to 1 if your C compiler doesn't accept -c and -o together. */ #undef NO_MINUS_C_MINUS_O /* Name of package */ #undef PACKAGE /* Define to the address where bug reports for this package should be sent. */ #undef PACKAGE_BUGREPORT /* Define to the full name of this package. */ #undef PACKAGE_NAME /* Define to the full name and version of this package. */ #undef PACKAGE_STRING /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME /* Define to the version of this package. */ #undef PACKAGE_VERSION /* The size of `char', as computed by sizeof. */ #undef SIZEOF_CHAR /* The size of `int', as computed by sizeof. */ #undef SIZEOF_INT /* The size of `long', as computed by sizeof. */ #undef SIZEOF_LONG /* The size of `short', as computed by sizeof. */ #undef SIZEOF_SHORT /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS /* Version number of package */ #undef VERSION /* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel). */ #if defined AC_APPLE_UNIVERSAL_BUILD # if defined __BIG_ENDIAN__ # define WORDS_BIGENDIAN 1 # endif #else # ifndef WORDS_BIGENDIAN # undef WORDS_BIGENDIAN # endif #endif /* Define to empty if `const' does not conform to ANSI C. */ #undef const /* Define to `unsigned int' if <sys/types.h> does not define. */ #undef size_t
0605tonton-test
pdfview/jni/jbig2dec/config.h
C
gpl3
3,143
LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := jbig2dec LOCAL_CFLAGS := -DHAVE_CONFIG_H LOCAL_SRC_FILES := \ jbig2.c \ jbig2_arith.c \ jbig2_arith_iaid.c \ jbig2_arith_int.c \ jbig2_generic.c \ jbig2_halftone.c \ jbig2_huffman.c \ jbig2_image.c \ jbig2_image_pbm.c \ jbig2_metadata.c \ jbig2_mmr.c \ jbig2_page.c \ jbig2_refinement.c \ jbig2_segment.c \ jbig2_symbol_dict.c \ jbig2_text.c \ jbig2dec.c \ sha1.c # getopt.c # getopt1.c # memcmp.c # snprintf.c # jbig2_image_png.c include $(BUILD_STATIC_LIBRARY)
0605tonton-test
pdfview/jni/jbig2dec/Android.mk
Makefile
gpl3
555
include $(call all-subdir-makefiles)
0605tonton-test
pdfview/jni/Android.mk
Makefile
gpl3
38
package com.jason.recognition; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Bundle; import android.os.SystemClock; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.Toast; public class DrawLineActivity extends Activity { private DrawView vw; ArrayList<Point> mCurrentPointArray; ArrayList<Point> mDrawPointArray; Recognition mRecoginition; private boolean mPressFirstBackKey = false; private Timer mTimer; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.main); // 기존 뷰는 사용하지 않는다. // 새로운 뷰를 생성하여 액티비티에 연결 vw = new DrawView(this); setContentView(vw); mCurrentPointArray = new ArrayList<Point>(); mDrawPointArray = new ArrayList<Point>(); } @Override public void onBackPressed() { // back key 한번 누르면 이전도형 clear // back key연속 두번 누르면 종료처리 if (mPressFirstBackKey == false) { mCurrentPointArray.clear(); // 마지막 도형의 시작 index를 찾는다. int sLastShapePos = 0; for (int i = 0; i < mDrawPointArray.size(); i++) { if (mDrawPointArray.get(i).mIsStart == true) { sLastShapePos = i; } } // 마지막 도형을 삭제한다. if( mDrawPointArray.size() > 0 ) { for (int i = mDrawPointArray.size()-1; i >= sLastShapePos; i--) { mDrawPointArray.remove(mDrawPointArray.get(i)); } vw.invalidate(); // onDraw() 호출 Toast.makeText(this, "last shape clear", 1).show(); } else { Toast.makeText(this, "already all shape clear", 1).show(); } mPressFirstBackKey = true; // back키가 2초내에 두번 눌렸는지 감지 TimerTask second = new TimerTask() { @Override public void run() { mTimer.cancel(); mTimer = null; mPressFirstBackKey = false; } }; if (mTimer != null) { mTimer.cancel(); mTimer = null; } mTimer = new Timer(); mTimer.schedule(second, 800); } else { super.onBackPressed(); } } public class Point { float x; float y; boolean mIsStart; // 시작점 여부 float mRadius; // 반지름 : 이 값이 0보다 크면 원이다. public Point() { this.x = 0; this.y = 0; this.mRadius = 0; this.mIsStart = false; } public Point(float x, float y, boolean isStart) { this.x = x; this.y = y; this.mRadius = 0; this.mIsStart = isStart; } } protected class Recognition { Context mContext; ArrayList<Point> mPointArray; // 모든 점이 저장됨 ArrayList<Point> mVertexList; // 꼭지점이 저장됨. /* * 각도는 mBasePoint와 현재 점의 각을 구한다. mBasePoint는 6개 이전 점으로 한다. */ Point mPointSum = new Point(); double mRadianAvr = 0; // 평균 각도 int mSumCount = 0; // sum된 개수 Point mBasePoint; // 각도를 잴 기준 점. public Recognition(Context aContext) { mContext = aContext; mPointArray = new ArrayList<Point>(); mVertexList = new ArrayList<Point>(); mBasePoint = new Point(); } // 점이 추가될때 호출되는 인터페이스 public void add(float x, float y, boolean isStart) { // mPointArray에 점을 추가 mPointArray.add(new Point(x, y, isStart)); // 첫번째 점이면 mBasePoint를 기준점 및 꼭지점으로 설정하고 종료 if (isStart == true) { mBasePoint = mPointArray.get(0); mVertexList.add(new Point(x, y, isStart)); return; } // 기준점으로부터 6개 이상 넘어가면 기준점을 6개 이전 점으로 설정한다. if (mSumCount > 6) { mBasePoint = mPointArray.get(mPointArray.size() - 6); } // mBasePoint와 현재 점의 각도를 구한다. float xChangeCur = x - mBasePoint.x; float yChangeCur = y - mBasePoint.y; // atan2함수를 이용하여 mBasePoint와 현재 점의 각도를 구한다. double sRadian = Math.atan2(yChangeCur, xChangeCur); //Log.i("test", " sRadian : " + sRadian + " sRadianAvr : " + mRadianAvr); // 꼭지점이 생기고 처음 3개는 꼭지점으로 인식하지 않는다. if (mSumCount >= 4) { // 이번 각도가 평균과 비슷한지 체크한다. // Math.PI = 3.14 // RadianAvr은 0이 0도, PI/2가 90도 PI가 180도, -PI/2가 -90도, -PI가 // -180도이다. // 180도와 -180도는 같은데 다르게 표현됨. // 아래에서 0.6은 30~40도 정도 될것 같음. if (sRadian < mRadianAvr + 0.6 && sRadian > mRadianAvr - 0.6) { // 각도가 비슷함. // 꼭지점 아님. } else if ((sRadian + Math.PI * 2) < mRadianAvr + 0.6 && (sRadian + Math.PI * 2) > mRadianAvr - 0.6) { // sRadina에 2pi를 더한것과 비슷함 // 꼭지점 아님. } else if ((sRadian - Math.PI * 2) < mRadianAvr + 0.6 && (sRadian - Math.PI * 2) > mRadianAvr - 0.6) { // sRadina에 2pi를 뺀것과 비슷함 // 꼭지점 아님. } else { // 꼭지점이다. // Log.i("test", "find Vertex "); // 각도는 꼭지점 부터 다시 재야 함으로 mRadianSum, mSumCount 는 초기화 함. mPointSum.x = 0; mPointSum.y = 0; mSumCount = 0; xChangeCur = 0; yChangeCur = 0; // 이전 point를 base point로 설정한다. mBasePoint = mPointArray.get(mPointArray.size() - 2); // 이전 point를 꼭지점으로 정한다. mVertexList .add(new Point(mBasePoint.x, mBasePoint.y, false)); } } // 좌표의 합을 구한다. mPointSum.x = mPointSum.x + xChangeCur; mPointSum.y = mPointSum.y + yChangeCur; mSumCount++; // 평균 각도를 구한다. mRadianAvr = Math.atan2(mPointSum.y, mPointSum.x); } public void end() { // 직선이면 마지막 점을 꼭지점으로 설정 if (mVertexList.size() == 1) { mBasePoint = mPointArray.get(mPointArray.size() - 1); mVertexList.add(new Point(mBasePoint.x, mBasePoint.y, false)); } // 직선이 아니면 처음과 끝이 어느정도 가까우면 // 처음 꼭지점을 마지막 꼭지점으로 입력 else { mBasePoint = mVertexList.get(0); Point sLastPoint = mPointArray.get(mPointArray.size() - 1); if ((mBasePoint.x - sLastPoint.x > -30 && mBasePoint.x - sLastPoint.x < 30) && (mBasePoint.y - sLastPoint.y > -30 && mBasePoint.y - sLastPoint.y < 30)) { mVertexList .add(new Point(mBasePoint.x, mBasePoint.y, false)); // Log.i("xx", "mVertexList.size " + mVertexList.size()); // 꼭지점이 5보다 크고 모든 내각이 180보다 작으면 원으로 인식한다. // 내각을 체크한다. boolean sIsCircle = true; float sInnerAngle = 0; for (int i = 1; i < mVertexList.size(); i++) { Point v1 = new Point(); if (i == 1) { v1.x = mVertexList.get(mVertexList.size() - 2).x - mVertexList.get(i - 1).x; v1.y = mVertexList.get(mVertexList.size() - 2).y - mVertexList.get(i - 1).y; } else { v1.x = mVertexList.get(i - 2).x - mVertexList.get(i - 1).x; v1.y = mVertexList.get(i - 2).y - mVertexList.get(i - 1).y; } Point v2 = new Point(); v2.x = mVertexList.get(i).x - mVertexList.get(i - 1).x; v2.y = mVertexList.get(i).y - mVertexList.get(i - 1).y; // 두 직선의 내각을 구한다. // 내각 = asin(x1y2-y1x2 / ( sqrt(x1*x1 + y1*y1) + // sqrt(x2*x2 + y2*y2) ) double sRadian = Math.asin((v1.x * v2.y - v1.y * v2.x) / (Math.sqrt(v1.x * v1.x + v1.y * v1.y) * Math .sqrt(v2.x * v2.x + v2.y * v2.y))); // Log.i("check circle", "sRadian " + sRadian); if (sRadian > 0) { if (i == 1) { sInnerAngle = 1; } else if (sInnerAngle == -1) { sIsCircle = false; } } else { if (i == 1) { sInnerAngle = -1; } else if (sInnerAngle == 1) { sIsCircle = false; } } } if (mVertexList.size() > 5 && sIsCircle == true) { // 원을 그리기 위해 중심점과 반지름을 구한다. Point sMin = new Point(); Point sMax = new Point(); Point sCenter = new Point(); // 원이면 x,y 축 각각 min + max /2 로 중심점을 구한다. // 초기값은 첫번째 점 sMin.x = mPointArray.get(0).x; sMin.y = mPointArray.get(0).y; sMax.x = mPointArray.get(0).x; sMax.y = mPointArray.get(0).y; for (int i = 1; i < mPointArray.size(); i++) { if (sMin.x > mPointArray.get(i).x) { sMin.x = mPointArray.get(i).x; } if (sMin.y > mPointArray.get(i).y) { sMin.y = mPointArray.get(i).y; } if (sMax.x < mPointArray.get(i).x) { sMax.x = mPointArray.get(i).x; } if (sMax.y < mPointArray.get(i).y) { sMax.y = mPointArray.get(i).y; } } sCenter.mIsStart = true; sCenter.x = (sMin.x + sMax.x) / 2; sCenter.y = (sMin.y + sMax.y) / 2; sCenter.mRadius = Math.abs((sCenter.x - sMin.x) / 2 + (sCenter.y - sMin.y) / 2); mVertexList.clear(); mVertexList.add(sCenter); } } else { // Log.i("###", "xx: " + (mBasePoint.x - sLastPoint.x) + // " yy: " + (mBasePoint.y - sLastPoint.y)); mVertexList.add(sLastPoint); } } // for(int i=0; i<mVertexList.size(); i++) // { // Log.i("end", "index " + i + // " x " + mVertexList.get(i).x + // " y " + mVertexList.get(i).y + // " isStart " + mVertexList.get(i).mIsStart); // } // mRecoginition.mVertexList가 직선이면 원과 접선을 그린것인지 체크해본다. if( mVertexList.size() == 2 ) { // size가 2이면 직선이다. // 기존에 그려진 원을 찾는다. for (int i = 0; i < mDrawPointArray.size(); i++) { final Point sCircle = mDrawPointArray.get(i); if (sCircle.mRadius > 0) { Log.i("접선", "기존원 x:" + sCircle.x + " y " + sCircle.y + " r : " + sCircle.mRadius ); // 원의 중심점과 직선의 거리를 구해서 반지름과 비교한다. // 점과 직선의 거리 : d = |ax1 + by1 + c| / root(a^2 + b^2) // 두점(x1,y1)(x2,y2)을 지나는 직선의 방정식 : y - y1 = (y2 - y1)/(x2 - x1) * (x - x1) // 직선의 방정식을 적용하면 시작점과 끝점이 없는 직선이 만들어진다. // 우리가 원하는 직선은 시잠점과 끝점이 있는데.. // 그래서 일단 쉽게 직선상의 점과 원의 중심점의 거리의 최소값을 구하는걸로 원의 중심점과 직선의 거리를 구한다. double sDistance = 0; double sMinDistance = 0; Point sStart = mVertexList.get(0); Point sEnd = mVertexList.get(1); Point sPointOfTangency = new Point(); // 직선을 100개의 점으로 나눴을때 다음점으로 이동되는 값 float xChange = (sEnd.x - sStart.x) / 100; float yChange = (sEnd.y - sStart.y) / 100; // 100개의 점에 대해서 원의 중심점과 거리 구하고 그중에서 최소값을 원과 직선의 거리로 인식한다. for( int j=0; j<100; j++ ) { // 두점의 거리 d = root( (x1-x2)^2 + (y1-y2)^2 ) sDistance = Math.pow(sCircle.x - (sStart.x + xChange * j), 2); sDistance += Math.pow(sCircle.y - (sStart.y + yChange * j), 2); sDistance = Math.sqrt( sDistance ); if( j == 0 || sDistance < sMinDistance ) { // MinDistance에 첫번째 값을 설정한다. // 두번째 부터는 sMinDistance 보다 작은 값이면 sMinDistance를 sDistance로 설정한다. sMinDistance = sDistance; sPointOfTangency.x = sStart.x + xChange * j; sPointOfTangency.y = sStart.y + yChange * j; } } Log.i("접선", "직선과 거리 : " + sMinDistance ); // 원과 직선의 오차가 20 이내면 접선으로 인식 if( Math.abs(sMinDistance - sCircle.mRadius) < 20 ) { Toast toast = Toast.makeText(mContext, "recognized Tangency", Toast.LENGTH_SHORT); toast.show(); Log.i("접선", "after show" ); ProcessTangent(sMinDistance, sCircle, sPointOfTangency); // 접선이 인식되었으면 다른 원과의 비교는 종료한다. } } } } } // 접선 처리하는 인터페이스 public void ProcessTangent(double sMinDistance, Point sCircle, Point sPointOfTangency) { Point sStart = mVertexList.get(0); Point sEnd = mVertexList.get(1); // 움직여야 하는 거리(sMove)는 반지름 - 직선과 원중심점 거리이다. double sMove = Math.sqrt(Math.pow(sCircle.mRadius - sMinDistance, 2) / 2); // 접선 이면 직선을 접선이 되도록 이동 // 원의 중심을 기준으로 접점 Point sTemp = new Point(sPointOfTangency.x - sCircle.x, sPointOfTangency.y - sCircle.y, false); // 접점의 각도 double sRadian = Math.atan2(sTemp.y, sTemp.x); // 각도가 sRadian이고 대각선이sMove일때 이동해야 하는 x값 double sMoveX = Math.cos(sRadian) * sMove; // 각도가 sRadian이고 대각선이sMove일때 이동해야 하는 y값 double sMoveY = Math.sin(sRadian) * sMove; Log.i("접선", "sMoveX " + sMoveX + " sMoveY " + sMoveY ); if( sMinDistance > sCircle.mRadius ) { // 직선을 원 중심으로 이동 sStart.x -= sMoveX; sEnd.x -= sMoveX; sStart.y -= sMoveY; sEnd.y -= sMoveY; } else { // 직선을 원 바깥으로 이동 sStart.x += sMoveX; sEnd.x += sMoveX; sStart.y += sMoveY; sEnd.y += sMoveY; } } } protected class DrawView extends View { Paint mPaint; // 페인트 객체 선언 Context mContext; public DrawView(Context context) { super(context); mContext = context; // 페인트 객체 생성 후 설정 mPaint = new Paint(); mPaint.setColor(Color.BLACK); mPaint.setStrokeWidth(3); mPaint.setAntiAlias(true); // 안티얼라이싱 mPaint.setStyle(Paint.Style.STROKE); } /** 터치이벤트를 받는 함수 */ @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mCurrentPointArray.add(new Point(event.getX(), event.getY(), true)); mRecoginition = new Recognition(mContext); mRecoginition.add(event.getX(), event.getY(), true); break; case MotionEvent.ACTION_MOVE: //Log.i("xx", "xy " + event.getX() + " : " + event.getY() ); mCurrentPointArray.add(new Point(event.getX(), event.getY(), false)); mRecoginition.add(event.getX(), event.getY(), false); break; case MotionEvent.ACTION_UP: mRecoginition.end(); mCurrentPointArray.clear(); mDrawPointArray.addAll(mRecoginition.mVertexList); break; } invalidate(); // onDraw() 호출 return true; } /** 화면을 계속 그려주는 함수 */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawColor(Color.WHITE); // 캔버스 배경색깔 설정 // 인식된 도형 그리기 for (int i = 0; i < mDrawPointArray.size(); i++) { if (mDrawPointArray.get(i).mIsStart == false) { // 이어서 그리고 있는 // 중이라면 canvas.drawLine(mDrawPointArray.get(i - 1).x, mDrawPointArray.get(i - 1).y, mDrawPointArray.get(i).x, mDrawPointArray.get(i).y, mPaint); // 이전 좌표에서 다음좌표까지 그린다. } if (mDrawPointArray.get(i).mRadius > 0) { // 원 그리기 canvas.drawCircle(mDrawPointArray.get(i).x, mDrawPointArray.get(i).y, mDrawPointArray.get(i).mRadius, mPaint); } else { // 점만 찍는다. canvas.drawPoint(mDrawPointArray.get(i).x, mDrawPointArray.get(i).y, mPaint); } } // 현재 터치중인 모양 그리기 for (int i = 0; i < mCurrentPointArray.size(); i++) { // 점만 찍는다. canvas.drawPoint(mCurrentPointArray.get(i).x, mCurrentPointArray.get(i).y, mPaint); } } } }
01-project-jason
trunk/recognition/src/com/jason/recognition/DrawLineActivity.java
Java
asf20
17,156
package com.jason.recognition; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import com.jason.recognition.*; /* * public class MainActivity extends Activity { * * @Override protected void onCreate(Bundle savedInstanceState) { * super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); * * Intent intent = new Intent(this, DrawLineActivity.class); * startActivity(intent); } * * } */
01-project-jason
trunk/recognition/src/com/jason/recognition/MainActivity.java
Java
asf20
512
/* * (C) Copyright 2007 Semihalf * * Written by: Rafal Jaworowski <raj@semihalf.com> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * */ #include <config.h> #include <command.h> #include <common.h> #include <malloc.h> #include <environment.h> #include <linux/types.h> #include <api_public.h> #include "api_private.h" #define DEBUG #undef DEBUG /***************************************************************************** * * This is the API core. * * API_ functions are part of U-Boot code and constitute the lowest level * calls: * * - they know what values they need as arguments * - their direct return value pertains to the API_ "shell" itself (0 on * success, some error code otherwise) * - if the call returns a value it is buried within arguments * ****************************************************************************/ #ifdef DEBUG #define debugf(fmt, args...) do { printf("%s(): ", __func__); printf(fmt, ##args); } while (0) #else #define debugf(fmt, args...) #endif typedef int (*cfp_t)(va_list argp); static int calls_no; /* * pseudo signature: * * int API_getc(int *c) */ static int API_getc(va_list ap) { int *c; if ((c = (int *)va_arg(ap, u_int32_t)) == NULL) return API_EINVAL; *c = getc(); return 0; } /* * pseudo signature: * * int API_tstc(int *c) */ static int API_tstc(va_list ap) { int *t; if ((t = (int *)va_arg(ap, u_int32_t)) == NULL) return API_EINVAL; *t = tstc(); return 0; } /* * pseudo signature: * * int API_putc(char *ch) */ static int API_putc(va_list ap) { char *c; if ((c = (char *)va_arg(ap, u_int32_t)) == NULL) return API_EINVAL; putc(*c); return 0; } /* * pseudo signature: * * int API_puts(char **s) */ static int API_puts(va_list ap) { char *s; if ((s = (char *)va_arg(ap, u_int32_t)) == NULL) return API_EINVAL; puts(s); return 0; } /* * pseudo signature: * * int API_reset(void) */ static int API_reset(va_list ap) { do_reset(NULL, 0, 0, NULL); /* NOT REACHED */ return 0; } /* * pseudo signature: * * int API_get_sys_info(struct sys_info *si) * * fill out the sys_info struct containing selected parameters about the * machine */ static int API_get_sys_info(va_list ap) { struct sys_info *si; si = (struct sys_info *)va_arg(ap, u_int32_t); if (si == NULL) return API_ENOMEM; return (platform_sys_info(si)) ? 0 : API_ENODEV; } /* * pseudo signature: * * int API_udelay(unsigned long *udelay) */ static int API_udelay(va_list ap) { unsigned long *d; if ((d = (unsigned long *)va_arg(ap, u_int32_t)) == NULL) return API_EINVAL; udelay(*d); return 0; } /* * pseudo signature: * * int API_get_timer(unsigned long *current, unsigned long *base) */ static int API_get_timer(va_list ap) { unsigned long *base, *cur; cur = (unsigned long *)va_arg(ap, u_int32_t); if (cur == NULL) return API_EINVAL; base = (unsigned long *)va_arg(ap, u_int32_t); if (base == NULL) return API_EINVAL; *cur = get_timer(*base); return 0; } /***************************************************************************** * * pseudo signature: * * int API_dev_enum(struct device_info *) * * * cookies uniqely identify the previously enumerated device instance and * provide a hint for what to inspect in current enum iteration: * * - net: &eth_device struct address from list pointed to by eth_devices * * - storage: block_dev_desc_t struct address from &ide_dev_desc[n], * &scsi_dev_desc[n] and similar tables * ****************************************************************************/ static int API_dev_enum(va_list ap) { struct device_info *di; /* arg is ptr to the device_info struct we are going to fill out */ di = (struct device_info *)va_arg(ap, u_int32_t); if (di == NULL) return API_EINVAL; if (di->cookie == NULL) { /* start over - clean up enumeration */ dev_enum_reset(); /* XXX shouldn't the name contain 'stor'? */ debugf("RESTART ENUM\n"); /* net device enumeration first */ if (dev_enum_net(di)) return 0; } /* * The hidden assumption is there can only be one active network * device and it is identified upon enumeration (re)start, so there's * no point in trying to find network devices in other cases than the * (re)start and hence the 'next' device can only be storage */ if (!dev_enum_storage(di)) /* make sure we mark there are no more devices */ di->cookie = NULL; return 0; } static int API_dev_open(va_list ap) { struct device_info *di; int err = 0; /* arg is ptr to the device_info struct */ di = (struct device_info *)va_arg(ap, u_int32_t); if (di == NULL) return API_EINVAL; /* Allow only one consumer of the device at a time */ if (di->state == DEV_STA_OPEN) return API_EBUSY; if (di->cookie == NULL) return API_ENODEV; if (di->type & DEV_TYP_STOR) err = dev_open_stor(di->cookie); else if (di->type & DEV_TYP_NET) err = dev_open_net(di->cookie); else err = API_ENODEV; if (!err) di->state = DEV_STA_OPEN; return err; } static int API_dev_close(va_list ap) { struct device_info *di; int err = 0; /* arg is ptr to the device_info struct */ di = (struct device_info *)va_arg(ap, u_int32_t); if (di == NULL) return API_EINVAL; if (di->state == DEV_STA_CLOSED) return 0; if (di->cookie == NULL) return API_ENODEV; if (di->type & DEV_TYP_STOR) err = dev_close_stor(di->cookie); else if (di->type & DEV_TYP_NET) err = dev_close_net(di->cookie); else /* * In case of unknown device we cannot change its state, so * only return error code */ err = API_ENODEV; if (!err) di->state = DEV_STA_CLOSED; return err; } /* * Notice: this is for sending network packets only, as U-Boot does not * support writing to storage at the moment (12.2007) * * pseudo signature: * * int API_dev_write( * struct device_info *di, * void *buf, * int *len * ) * * buf: ptr to buffer from where to get the data to send * * len: length of packet to be sent (in bytes) * */ static int API_dev_write(va_list ap) { struct device_info *di; void *buf; int *len; int err = 0; /* 1. arg is ptr to the device_info struct */ di = (struct device_info *)va_arg(ap, u_int32_t); if (di == NULL) return API_EINVAL; /* XXX should we check if device is open? i.e. the ->state ? */ if (di->cookie == NULL) return API_ENODEV; /* 2. arg is ptr to buffer from where to get data to write */ buf = (void *)va_arg(ap, u_int32_t); if (buf == NULL) return API_EINVAL; /* 3. arg is length of buffer */ len = (int *)va_arg(ap, u_int32_t); if (len == NULL) return API_EINVAL; if (*len <= 0) return API_EINVAL; if (di->type & DEV_TYP_STOR) /* * write to storage is currently not supported by U-Boot: * no storage device implements block_write() method */ return API_ENODEV; else if (di->type & DEV_TYP_NET) err = dev_write_net(di->cookie, buf, *len); else err = API_ENODEV; return err; } /* * pseudo signature: * * int API_dev_read( * struct device_info *di, * void *buf, * size_t *len, * unsigned long *start * size_t *act_len * ) * * buf: ptr to buffer where to put the read data * * len: ptr to length to be read * - network: len of packet to read (in bytes) * - storage: # of blocks to read (can vary in size depending on define) * * start: ptr to start block (only used for storage devices, ignored for * network) * * act_len: ptr to where to put the len actually read */ static int API_dev_read(va_list ap) { struct device_info *di; void *buf; lbasize_t *len_stor, *act_len_stor; lbastart_t *start; int *len_net, *act_len_net; /* 1. arg is ptr to the device_info struct */ di = (struct device_info *)va_arg(ap, u_int32_t); if (di == NULL) return API_EINVAL; /* XXX should we check if device is open? i.e. the ->state ? */ if (di->cookie == NULL) return API_ENODEV; /* 2. arg is ptr to buffer from where to put the read data */ buf = (void *)va_arg(ap, u_int32_t); if (buf == NULL) return API_EINVAL; if (di->type & DEV_TYP_STOR) { /* 3. arg - ptr to var with # of blocks to read */ len_stor = (lbasize_t *)va_arg(ap, u_int32_t); if (!len_stor) return API_EINVAL; if (*len_stor <= 0) return API_EINVAL; /* 4. arg - ptr to var with start block */ start = (lbastart_t *)va_arg(ap, u_int32_t); /* 5. arg - ptr to var where to put the len actually read */ act_len_stor = (lbasize_t *)va_arg(ap, u_int32_t); if (!act_len_stor) return API_EINVAL; *act_len_stor = dev_read_stor(di->cookie, buf, *len_stor, *start); } else if (di->type & DEV_TYP_NET) { /* 3. arg points to the var with length of packet to read */ len_net = (int *)va_arg(ap, u_int32_t); if (!len_net) return API_EINVAL; if (*len_net <= 0) return API_EINVAL; /* 4. - ptr to var where to put the len actually read */ act_len_net = (int *)va_arg(ap, u_int32_t); if (!act_len_net) return API_EINVAL; *act_len_net = dev_read_net(di->cookie, buf, *len_net); } else return API_ENODEV; return 0; } /* * pseudo signature: * * int API_env_get(const char *name, char **value) * * name: ptr to name of env var */ static int API_env_get(va_list ap) { char *name, **value; if ((name = (char *)va_arg(ap, u_int32_t)) == NULL) return API_EINVAL; if ((value = (char **)va_arg(ap, u_int32_t)) == NULL) return API_EINVAL; *value = getenv(name); return 0; } /* * pseudo signature: * * int API_env_set(const char *name, const char *value) * * name: ptr to name of env var * * value: ptr to value to be set */ static int API_env_set(va_list ap) { char *name, *value; if ((name = (char *)va_arg(ap, u_int32_t)) == NULL) return API_EINVAL; if ((value = (char *)va_arg(ap, u_int32_t)) == NULL) return API_EINVAL; setenv(name, value); return 0; } /* * pseudo signature: * * int API_env_enum(const char *last, char **next) * * last: ptr to name of env var found in last iteration */ static int API_env_enum(va_list ap) { int i, n; char *last, **next; last = (char *)va_arg(ap, u_int32_t); if ((next = (char **)va_arg(ap, u_int32_t)) == NULL) return API_EINVAL; if (last == NULL) /* start over */ *next = ((char *)env_get_addr(0)); else { *next = last; for (i = 0; env_get_char(i) != '\0'; i = n + 1) { for (n = i; env_get_char(n) != '\0'; ++n) { if (n >= CONFIG_ENV_SIZE) { /* XXX shouldn't we set *next = NULL?? */ return 0; } } if (envmatch((uchar *)last, i) < 0) continue; /* try to get next name */ i = n + 1; if (env_get_char(i) == '\0') { /* no more left */ *next = NULL; return 0; } *next = ((char *)env_get_addr(i)); return 0; } } return 0; } /* * pseudo signature: * * int API_display_get_info(int type, struct display_info *di) */ static int API_display_get_info(va_list ap) { int type; struct display_info *di; type = va_arg(ap, int); di = va_arg(ap, struct display_info *); return display_get_info(type, di); } /* * pseudo signature: * * int API_display_draw_bitmap(ulong bitmap, int x, int y) */ static int API_display_draw_bitmap(va_list ap) { ulong bitmap; int x, y; bitmap = va_arg(ap, ulong); x = va_arg(ap, int); y = va_arg(ap, int); return display_draw_bitmap(bitmap, x, y); } /* * pseudo signature: * * void API_display_clear(void) */ static int API_display_clear(va_list ap) { display_clear(); return 0; } static cfp_t calls_table[API_MAXCALL] = { NULL, }; /* * The main syscall entry point - this is not reentrant, only one call is * serviced until finished. * * e.g. syscall(1, int *, u_int32_t, u_int32_t, u_int32_t, u_int32_t); * * call: syscall number * * retval: points to the return value placeholder, this is the place the * syscall puts its return value, if NULL the caller does not * expect a return value * * ... syscall arguments (variable number) * * returns: 0 if the call not found, 1 if serviced */ int syscall(int call, int *retval, ...) { va_list ap; int rv; if (call < 0 || call >= calls_no) { debugf("invalid call #%d\n", call); return 0; } if (calls_table[call] == NULL) { debugf("syscall #%d does not have a handler\n", call); return 0; } va_start(ap, retval); rv = calls_table[call](ap); if (retval != NULL) *retval = rv; return 1; } void api_init(void) { struct api_signature *sig = NULL; /* TODO put this into linker set one day... */ calls_table[API_RSVD] = NULL; calls_table[API_GETC] = &API_getc; calls_table[API_PUTC] = &API_putc; calls_table[API_TSTC] = &API_tstc; calls_table[API_PUTS] = &API_puts; calls_table[API_RESET] = &API_reset; calls_table[API_GET_SYS_INFO] = &API_get_sys_info; calls_table[API_UDELAY] = &API_udelay; calls_table[API_GET_TIMER] = &API_get_timer; calls_table[API_DEV_ENUM] = &API_dev_enum; calls_table[API_DEV_OPEN] = &API_dev_open; calls_table[API_DEV_CLOSE] = &API_dev_close; calls_table[API_DEV_READ] = &API_dev_read; calls_table[API_DEV_WRITE] = &API_dev_write; calls_table[API_ENV_GET] = &API_env_get; calls_table[API_ENV_SET] = &API_env_set; calls_table[API_ENV_ENUM] = &API_env_enum; calls_table[API_DISPLAY_GET_INFO] = &API_display_get_info; calls_table[API_DISPLAY_DRAW_BITMAP] = &API_display_draw_bitmap; calls_table[API_DISPLAY_CLEAR] = &API_display_clear; calls_no = API_MAXCALL; debugf("API initialized with %d calls\n", calls_no); dev_stor_init(); /* * Produce the signature so the API consumers can find it */ sig = malloc(sizeof(struct api_signature)); if (sig == NULL) { printf("API: could not allocate memory for the signature!\n"); return; } debugf("API sig @ 0x%08x\n", sig); memcpy(sig->magic, API_SIG_MAGIC, 8); sig->version = API_SIG_VERSION; sig->syscall = &syscall; sig->checksum = 0; sig->checksum = crc32(0, (unsigned char *)sig, sizeof(struct api_signature)); debugf("syscall entry: 0x%08x\n", sig->syscall); } void platform_set_mr(struct sys_info *si, unsigned long start, unsigned long size, int flags) { int i; if (!si->mr || !size || (flags == 0)) return; /* find free slot */ for (i = 0; i < si->mr_no; i++) if (si->mr[i].flags == 0) { /* insert new mem region */ si->mr[i].start = start; si->mr[i].size = size; si->mr[i].flags = flags; return; } }
1001-study-uboot
api/api.c
C
gpl3
15,037
/* * (C) Copyright 2007 Semihalf * * Written by: Rafal Jaworowski <raj@semihalf.com> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * */ #include <config.h> #include <common.h> #include <net.h> #include <linux/types.h> #include <api_public.h> DECLARE_GLOBAL_DATA_PTR; #define DEBUG #undef DEBUG #ifdef DEBUG #define debugf(fmt, args...) do { printf("%s(): ", __func__); printf(fmt, ##args); } while (0) #else #define debugf(fmt, args...) #endif #define errf(fmt, args...) do { printf("ERROR @ %s(): ", __func__); printf(fmt, ##args); } while (0) static int dev_valid_net(void *cookie) { return ((void *)eth_get_dev() == cookie) ? 1 : 0; } int dev_open_net(void *cookie) { if (!dev_valid_net(cookie)) return API_ENODEV; if (eth_init(gd->bd) < 0) return API_EIO; return 0; } int dev_close_net(void *cookie) { if (!dev_valid_net(cookie)) return API_ENODEV; eth_halt(); return 0; } /* * There can only be one active eth interface at a time - use what is * currently set to eth_current */ int dev_enum_net(struct device_info *di) { struct eth_device *eth_current = eth_get_dev(); di->type = DEV_TYP_NET; di->cookie = (void *)eth_current; if (di->cookie == NULL) return 0; memcpy(di->di_net.hwaddr, eth_current->enetaddr, 6); debugf("device found, returning cookie 0x%08x\n", (u_int32_t)di->cookie); return 1; } int dev_write_net(void *cookie, void *buf, int len) { /* XXX verify that cookie points to a valid net device??? */ return eth_send(buf, len); } int dev_read_net(void *cookie, void *buf, int len) { /* XXX verify that cookie points to a valid net device??? */ return eth_receive(buf, len); }
1001-study-uboot
api/api_net.c
C
gpl3
2,401
/* * Copyright (c) 2011 The Chromium OS Authors. * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <common.h> #include <api_public.h> #include <lcd.h> #include <video_font.h> /* Get font width and height */ /* lcd.h needs BMP_LOGO_HEIGHT to calculate CONSOLE_ROWS */ #if defined(CONFIG_LCD_LOGO) && !defined(CONFIG_LCD_INFO_BELOW_LOGO) #include <bmp_logo.h> #endif /* TODO(clchiou): add support of video device */ int display_get_info(int type, struct display_info *di) { if (!di) return API_EINVAL; switch (type) { default: debug("%s: unsupport display device type: %d\n", __FILE__, type); return API_ENODEV; #ifdef CONFIG_LCD case DISPLAY_TYPE_LCD: di->pixel_width = panel_info.vl_col; di->pixel_height = panel_info.vl_row; di->screen_rows = CONSOLE_ROWS; di->screen_cols = CONSOLE_COLS; break; #endif } di->type = type; return 0; } int display_draw_bitmap(ulong bitmap, int x, int y) { if (!bitmap) return API_EINVAL; #ifdef CONFIG_LCD return lcd_display_bitmap(bitmap, x, y); #else return API_ENODEV; #endif } void display_clear(void) { #ifdef CONFIG_LCD lcd_clear(); #endif }
1001-study-uboot
api/api_display.c
C
gpl3
1,879
/* * (C) Copyright 2007 Semihalf * * Written by: Rafal Jaworowski <raj@semihalf.com> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * This file contains routines that fetch data from ARM-dependent sources * (bd_info etc.) * */ #include <config.h> #include <linux/types.h> #include <api_public.h> #include <asm/u-boot.h> #include <asm/global_data.h> #include "api_private.h" DECLARE_GLOBAL_DATA_PTR; /* * Important notice: handling of individual fields MUST be kept in sync with * include/asm-arm/u-boot.h and include/asm-arm/global_data.h, so any changes * need to reflect their current state and layout of structures involved! */ int platform_sys_info(struct sys_info *si) { int i; for (i = 0; i < CONFIG_NR_DRAM_BANKS; i++) platform_set_mr(si, gd->bd->bi_dram[i].start, gd->bd->bi_dram[i].size, MR_ATTR_DRAM); return 1; }
1001-study-uboot
api/api_platform-arm.c
C
gpl3
1,605
# # (C) Copyright 2007 Semihalf # # See file CREDITS for list of people who contributed to this # project. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundatio; either version 2 of # the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # include $(TOPDIR)/config.mk LIB = $(obj)libapi.o COBJS-$(CONFIG_API) += api.o api_display.o api_net.o api_storage.o \ api_platform-$(ARCH).o COBJS := $(COBJS-y) SRCS := $(COBJS:.o=.c) OBJS := $(addprefix $(obj),$(COBJS)) $(LIB): $(obj).depend $(OBJS) $(call cmd_link_o_target, $(OBJS)) # defines $(obj).depend target include $(SRCTREE)/rules.mk sinclude $(obj).depend
1001-study-uboot
api/Makefile
Makefile
gpl3
1,195
/* * (C) Copyright 2007 Semihalf * * Written by: Rafal Jaworowski <raj@semihalf.com> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * This file contains routines that fetch data from PowerPC-dependent sources * (bd_info etc.) * */ #include <config.h> #include <linux/types.h> #include <api_public.h> #include <asm/u-boot.h> #include <asm/global_data.h> #include "api_private.h" DECLARE_GLOBAL_DATA_PTR; /* * Important notice: handling of individual fields MUST be kept in sync with * include/asm-ppc/u-boot.h and include/asm-ppc/global_data.h, so any changes * need to reflect their current state and layout of structures involved! */ int platform_sys_info(struct sys_info *si) { si->clk_bus = gd->bus_clk; si->clk_cpu = gd->cpu_clk; #if defined(CONFIG_5xx) || defined(CONFIG_8xx) || defined(CONFIG_8260) || \ defined(CONFIG_E500) || defined(CONFIG_MPC86xx) #define bi_bar bi_immr_base #elif defined(CONFIG_MPC5xxx) #define bi_bar bi_mbar_base #elif defined(CONFIG_MPC83xx) #define bi_bar bi_immrbar #elif defined(CONFIG_MPC8220) #define bi_bar bi_mbar_base #endif #if defined(bi_bar) si->bar = gd->bd->bi_bar; #undef bi_bar #else si->bar = 0; #endif platform_set_mr(si, gd->bd->bi_memstart, gd->bd->bi_memsize, MR_ATTR_DRAM); platform_set_mr(si, gd->bd->bi_flashstart, gd->bd->bi_flashsize, MR_ATTR_FLASH); platform_set_mr(si, gd->bd->bi_sramstart, gd->bd->bi_sramsize, MR_ATTR_SRAM); return 1; }
1001-study-uboot
api/api_platform-powerpc.c
C
gpl3
2,184
/* * (C) Copyright 2007-2008 Semihalf * * Written by: Rafal Jaworowski <raj@semihalf.com> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * */ #include <config.h> #include <common.h> #include <api_public.h> #if defined(CONFIG_CMD_USB) && defined(CONFIG_USB_STORAGE) #include <usb.h> #endif #define DEBUG #undef DEBUG #ifdef DEBUG #define debugf(fmt, args...) do { printf("%s(): ", __func__); printf(fmt, ##args); } while (0) #else #define debugf(fmt, args...) #endif #define errf(fmt, args...) do { printf("ERROR @ %s(): ", __func__); printf(fmt, ##args); } while (0) #define ENUM_IDE 0 #define ENUM_USB 1 #define ENUM_SCSI 2 #define ENUM_MMC 3 #define ENUM_SATA 4 #define ENUM_MAX 5 struct stor_spec { int max_dev; int enum_started; int enum_ended; int type; /* "external" type: DT_STOR_{IDE,USB,etc} */ char *name; }; static struct stor_spec specs[ENUM_MAX] = { { 0, 0, 0, 0, "" }, }; void dev_stor_init(void) { #if defined(CONFIG_CMD_IDE) specs[ENUM_IDE].max_dev = CONFIG_SYS_IDE_MAXDEVICE; specs[ENUM_IDE].enum_started = 0; specs[ENUM_IDE].enum_ended = 0; specs[ENUM_IDE].type = DEV_TYP_STOR | DT_STOR_IDE; specs[ENUM_IDE].name = "ide"; #endif #if defined(CONFIG_CMD_MMC) specs[ENUM_MMC].max_dev = CONFIG_SYS_MMC_MAX_DEVICE; specs[ENUM_MMC].enum_started = 0; specs[ENUM_MMC].enum_ended = 0; specs[ENUM_MMC].type = DEV_TYP_STOR | DT_STOR_MMC; specs[ENUM_MMC].name = "mmc"; #endif #if defined(CONFIG_CMD_SATA) specs[ENUM_SATA].max_dev = CONFIG_SYS_SATA_MAX_DEVICE; specs[ENUM_SATA].enum_started = 0; specs[ENUM_SATA].enum_ended = 0; specs[ENUM_SATA].type = DEV_TYP_STOR | DT_STOR_SATA; specs[ENUM_SATA].name = "sata"; #endif #if defined(CONFIG_CMD_SCSI) specs[ENUM_SCSI].max_dev = CONFIG_SYS_SCSI_MAX_DEVICE; specs[ENUM_SCSI].enum_started = 0; specs[ENUM_SCSI].enum_ended = 0; specs[ENUM_SCSI].type = DEV_TYP_STOR | DT_STOR_SCSI; specs[ENUM_SCSI].name = "scsi"; #endif #if defined(CONFIG_CMD_USB) && defined(CONFIG_USB_STORAGE) specs[ENUM_USB].max_dev = USB_MAX_STOR_DEV; specs[ENUM_USB].enum_started = 0; specs[ENUM_USB].enum_ended = 0; specs[ENUM_USB].type = DEV_TYP_STOR | DT_STOR_USB; specs[ENUM_USB].name = "usb"; #endif } /* * Finds next available device in the storage group * * type: storage group type - ENUM_IDE, ENUM_SCSI etc. * * first: if 1 the first device in the storage group is returned (if * exists), if 0 the next available device is searched * * more: returns 0/1 depending if there are more devices in this group * available (for future iterations) * * returns: 0/1 depending if device found in this iteration */ static int dev_stor_get(int type, int first, int *more, struct device_info *di) { int found = 0; *more = 0; int i; block_dev_desc_t *dd; if (first) { di->cookie = (void *)get_dev(specs[type].name, 0); if (di->cookie == NULL) return 0; else found = 1; } else { for (i = 0; i < specs[type].max_dev; i++) if (di->cookie == (void *)get_dev(specs[type].name, i)) { /* previous cookie found -- advance to the * next device, if possible */ if (++i >= specs[type].max_dev) { /* out of range, no more to enum */ di->cookie = NULL; break; } di->cookie = (void *)get_dev(specs[type].name, i); if (di->cookie == NULL) return 0; else found = 1; /* provide hint if there are more devices in * this group to enumerate */ if ((i + 1) < specs[type].max_dev) *more = 1; break; } } if (found) { di->type = specs[type].type; if (di->cookie != NULL) { dd = (block_dev_desc_t *)di->cookie; if (dd->type == DEV_TYPE_UNKNOWN) { debugf("device instance exists, but is not active.."); found = 0; } else { di->di_stor.block_count = dd->lba; di->di_stor.block_size = dd->blksz; } } } else di->cookie = NULL; return found; } /* * returns: ENUM_IDE, ENUM_USB etc. based on block_dev_desc_t */ static int dev_stor_type(block_dev_desc_t *dd) { int i, j; for (i = ENUM_IDE; i < ENUM_MAX; i++) for (j = 0; j < specs[i].max_dev; j++) if (dd == get_dev(specs[i].name, j)) return i; return ENUM_MAX; } /* * returns: 0/1 whether cookie points to some device in this group */ static int dev_is_stor(int type, struct device_info *di) { return (dev_stor_type(di->cookie) == type) ? 1 : 0; } static int dev_enum_stor(int type, struct device_info *di) { int found = 0, more = 0; debugf("called, type %d\n", type); /* * Formulae for enumerating storage devices: * 1. if cookie (hint from previous enum call) is NULL we start again * with enumeration, so return the first available device, done. * * 2. if cookie is not NULL, check if it identifies some device in * this group: * * 2a. if cookie is a storage device from our group (IDE, USB etc.), * return next available (if exists) in this group * * 2b. if it isn't device from our group, check if such devices were * ever enumerated before: * - if not, return the first available device from this group * - else return 0 */ if (di->cookie == NULL) { debugf("group%d - enum restart\n", type); /* * 1. Enumeration (re-)started: take the first available * device, if exists */ found = dev_stor_get(type, 1, &more, di); specs[type].enum_started = 1; } else if (dev_is_stor(type, di)) { debugf("group%d - enum continued for the next device\n", type); if (specs[type].enum_ended) { debugf("group%d - nothing more to enum!\n", type); return 0; } /* 2a. Attempt to take a next available device in the group */ found = dev_stor_get(type, 0, &more, di); } else { if (specs[type].enum_ended) { debugf("group %d - already enumerated, skipping\n", type); return 0; } debugf("group%d - first time enum\n", type); if (specs[type].enum_started == 0) { /* * 2b. If enumerating devices in this group did not * happen before, it means the cookie pointed to a * device frome some other group (another storage * group, or network); in this case try to take the * first available device from our group */ specs[type].enum_started = 1; /* * Attempt to take the first device in this group: *'first element' flag is set */ found = dev_stor_get(type, 1, &more, di); } else { errf("group%d - out of order iteration\n", type); found = 0; more = 0; } } /* * If there are no more devices in this group, consider its * enumeration finished */ specs[type].enum_ended = (!more) ? 1 : 0; if (found) debugf("device found, returning cookie 0x%08x\n", (u_int32_t)di->cookie); else debugf("no device found\n"); return found; } void dev_enum_reset(void) { int i; for (i = 0; i < ENUM_MAX; i ++) { specs[i].enum_started = 0; specs[i].enum_ended = 0; } } int dev_enum_storage(struct device_info *di) { int i; /* * check: ide, usb, scsi, mmc */ for (i = ENUM_IDE; i < ENUM_MAX; i ++) { if (dev_enum_stor(i, di)) return 1; } return 0; } static int dev_stor_is_valid(int type, block_dev_desc_t *dd) { int i; for (i = 0; i < specs[type].max_dev; i++) if (dd == get_dev(specs[type].name, i)) if (dd->type != DEV_TYPE_UNKNOWN) return 1; return 0; } int dev_open_stor(void *cookie) { int type = dev_stor_type(cookie); if (type == ENUM_MAX) return API_ENODEV; if (dev_stor_is_valid(type, (block_dev_desc_t *)cookie)) return 0; return API_ENODEV; } int dev_close_stor(void *cookie) { /* * Not much to do as we actually do not alter storage devices upon * close */ return 0; } static int dev_stor_index(block_dev_desc_t *dd) { int i, type; type = dev_stor_type(dd); for (i = 0; i < specs[type].max_dev; i++) if (dd == get_dev(specs[type].name, i)) return i; return (specs[type].max_dev); } lbasize_t dev_read_stor(void *cookie, void *buf, lbasize_t len, lbastart_t start) { int type; block_dev_desc_t *dd = (block_dev_desc_t *)cookie; if ((type = dev_stor_type(dd)) == ENUM_MAX) return 0; if (!dev_stor_is_valid(type, dd)) return 0; if ((dd->block_read) == NULL) { debugf("no block_read() for device 0x%08x\n", cookie); return 0; } return (dd->block_read(dev_stor_index(dd), start, len, buf)); }
1001-study-uboot
api/api_storage.c
C
gpl3
8,996
/* * (C) Copyright 2007 Semihalf * * Written by: Rafal Jaworowski <raj@semihalf.com> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * */ #ifndef _API_PRIVATE_H_ #define _API_PRIVATE_H_ void api_init(void); void platform_set_mr(struct sys_info *, unsigned long, unsigned long, int); int platform_sys_info(struct sys_info *); void dev_enum_reset(void); int dev_enum_storage(struct device_info *); int dev_enum_net(struct device_info *); int dev_open_stor(void *); int dev_open_net(void *); int dev_close_stor(void *); int dev_close_net(void *); lbasize_t dev_read_stor(void *, void *, lbasize_t, lbastart_t); int dev_read_net(void *, void *, int); int dev_write_net(void *, void *, int); void dev_stor_init(void); int display_get_info(int type, struct display_info *di); int display_draw_bitmap(ulong bitmap, int x, int y); void display_clear(void); #endif /* _API_PRIVATE_H_ */
1001-study-uboot
api/api_private.h
C
gpl3
1,640
#!/bin/bash # Tool mainly for U-Boot Quality Assurance: build one or more board # configurations with minimal verbosity, showing only warnings and # errors. usage() { # if exiting with 0, write to stdout, else write to stderr local ret=${1:-0} [ "${ret}" -eq 1 ] && exec 1>&2 cat <<-EOF Usage: MAKEALL [options] [--] [boards-to-build] Options: -a ARCH, --arch ARCH Build all boards with arch ARCH -c CPU, --cpu CPU Build all boards with cpu CPU -v VENDOR, --vendor VENDOR Build all boards with vendor VENDOR -s SOC, --soc SOC Build all boards with soc SOC -l, --list List all targets to be built -h, --help This help output Selections by these options are logically ANDed; if the same option is used repeatedly, such selections are ORed. So "-v FOO -v BAR" will select all configurations where the vendor is either FOO or BAR. Any additional arguments specified on the command line are always build additionally. See the boards.cfg file for more info. If no boards are specified, then the default is "powerpc". Environment variables: BUILD_NCPUS number of parallel make jobs (default: auto) CROSS_COMPILE cross-compiler toolchain prefix (default: "") MAKEALL_LOGDIR output all logs to here (default: ./LOG/) BUILD_DIR output build directory (default: ./) Examples: - build all Power Architecture boards: MAKEALL -a powerpc MAKEALL --arch powerpc MAKEALL powerpc - build all PowerPC boards manufactured by vendor "esd": MAKEALL -a powerpc -v esd - build all PowerPC boards manufactured either by "keymile" or "siemens": MAKEALL -a powerpc -v keymile -v siemens - build all Freescale boards with MPC83xx CPUs, plus all 4xx boards: MAKEALL -c mpc83xx -v freescale 4xx EOF exit ${ret} } SHORT_OPTS="ha:c:v:s:l" LONG_OPTS="help,arch:,cpu:,vendor:,soc:,list" # Option processing based on util-linux-2.13/getopt-parse.bash # Note that we use `"$@"' to let each command-line parameter expand to a # separate word. The quotes around `$@' are essential! # We need TEMP as the `eval set --' would nuke the return value of # getopt. TEMP=`getopt -o ${SHORT_OPTS} --long ${LONG_OPTS} \ -n 'MAKEALL' -- "$@"` [ $? != 0 ] && usage 1 # Note the quotes around `$TEMP': they are essential! eval set -- "$TEMP" SELECTED='' ONLY_LIST='' while true ; do case "$1" in -a|--arch) # echo "Option ARCH: argument \`$2'" if [ "$opt_a" ] ; then opt_a="${opt_a%)} || \$2 == \"$2\")" else opt_a="(\$2 == \"$2\")" fi SELECTED='y' shift 2 ;; -c|--cpu) # echo "Option CPU: argument \`$2'" if [ "$opt_c" ] ; then opt_c="${opt_c%)} || \$3 == \"$2\")" else opt_c="(\$3 == \"$2\")" fi SELECTED='y' shift 2 ;; -s|--soc) # echo "Option SoC: argument \`$2'" if [ "$opt_s" ] ; then opt_s="${opt_s%)} || \$6 == \"$2\")" else opt_s="(\$6 == \"$2\")" fi SELECTED='y' shift 2 ;; -v|--vendor) # echo "Option VENDOR: argument \`$2'" if [ "$opt_v" ] ; then opt_v="${opt_v%)} || \$5 == \"$2\")" else opt_v="(\$5 == \"$2\")" fi SELECTED='y' shift 2 ;; -l|--list) ONLY_LIST='y' shift ;; -h|--help) usage ;; --) shift ; break ;; *) echo "Internal error!" >&2 ; exit 1 ;; esac done # echo "Remaining arguments:" # for arg do echo '--> '"\`$arg'" ; done FILTER="\$1 !~ /^#/" [ "$opt_a" ] && FILTER="${FILTER} && $opt_a" [ "$opt_c" ] && FILTER="${FILTER} && $opt_c" [ "$opt_s" ] && FILTER="${FILTER} && $opt_s" [ "$opt_v" ] && FILTER="${FILTER} && $opt_v" if [ "$SELECTED" ] ; then SELECTED=$(awk '('"$FILTER"') { print $1 }' boards.cfg) # Make sure some boards from boards.cfg are actually found if [ -z "$SELECTED" ] ; then echo "Error: No boards selected, invalid arguments" exit 1 fi fi ######################################################################### # Print statistics when we exit trap exit 1 2 3 15 trap print_stats 0 # Determine number of CPU cores if no default was set : ${BUILD_NCPUS:="`getconf _NPROCESSORS_ONLN`"} if [ "$BUILD_NCPUS" -gt 1 ] then JOBS="-j $((BUILD_NCPUS + 1))" else JOBS="" fi if [ "${CROSS_COMPILE}" ] ; then MAKE="make CROSS_COMPILE=${CROSS_COMPILE}" else MAKE=make fi if [ "${MAKEALL_LOGDIR}" ] ; then LOG_DIR=${MAKEALL_LOGDIR} else LOG_DIR="LOG" fi if [ ! "${BUILD_DIR}" ] ; then BUILD_DIR="." fi [ -d ${LOG_DIR} ] || mkdir ${LOG_DIR} || exit 1 LIST="" # Keep track of the number of builds and errors ERR_CNT=0 ERR_LIST="" TOTAL_CNT=0 RC=0 # Helper funcs for parsing boards.cfg boards_by_field() { awk \ -v field="$1" \ -v select="$2" \ '($1 !~ /^#/ && $field == select) { print $1 }' \ boards.cfg } boards_by_arch() { boards_by_field 2 "$@" ; } boards_by_cpu() { boards_by_field 3 "$@" ; } boards_by_soc() { boards_by_field 6 "$@" ; } ######################################################################### ## MPC5xx Systems ######################################################################### LIST_5xx="$(boards_by_cpu mpc5xx)" ######################################################################### ## MPC5xxx Systems ######################################################################### LIST_5xxx="$(boards_by_cpu mpc5xxx)" ######################################################################### ## MPC512x Systems ######################################################################### LIST_512x="$(boards_by_cpu mpc512x)" ######################################################################### ## MPC8xx Systems ######################################################################### LIST_8xx="$(boards_by_cpu mpc8xx)" ######################################################################### ## PPC4xx Systems ######################################################################### LIST_4xx="$(boards_by_cpu ppc4xx)" ######################################################################### ## MPC8220 Systems ######################################################################### LIST_8220="$(boards_by_cpu mpc8220)" ######################################################################### ## MPC824x Systems ######################################################################### LIST_824x="$(boards_by_cpu mpc824x)" ######################################################################### ## MPC8260 Systems (includes 8250, 8255 etc.) ######################################################################### LIST_8260="$(boards_by_cpu mpc8260)" ######################################################################### ## MPC83xx Systems (includes 8349, etc.) ######################################################################### LIST_83xx="$(boards_by_cpu mpc83xx)" ######################################################################### ## MPC85xx Systems (includes 8540, 8560 etc.) ######################################################################### LIST_85xx="$(boards_by_cpu mpc85xx)" ######################################################################### ## MPC86xx Systems ######################################################################### LIST_86xx="$(boards_by_cpu mpc86xx)" ######################################################################### ## 74xx/7xx Systems ######################################################################### LIST_74xx_7xx="$(boards_by_cpu 74xx_7xx)" ######################################################################### ## PowerPC groups ######################################################################### LIST_TSEC=" \ ${LIST_83xx} \ ${LIST_85xx} \ ${LIST_86xx} \ " LIST_powerpc=" \ ${LIST_5xx} \ ${LIST_512x} \ ${LIST_5xxx} \ ${LIST_8xx} \ ${LIST_8220} \ ${LIST_824x} \ ${LIST_8260} \ ${LIST_83xx} \ ${LIST_85xx} \ ${LIST_86xx} \ ${LIST_4xx} \ ${LIST_74xx_7xx}\ " # Alias "ppc" -> "powerpc" to not break compatibility with older scripts # still using "ppc" instead of "powerpc" LIST_ppc=" \ ${LIST_powerpc} \ " ######################################################################### ## StrongARM Systems ######################################################################### LIST_SA="$(boards_by_cpu sa1100)" ######################################################################### ## ARM9 Systems ######################################################################### LIST_ARM9="$(boards_by_cpu arm920t) \ $(boards_by_cpu arm926ejs) \ $(boards_by_cpu arm925t) \ " ######################################################################### ## ARM11 Systems ######################################################################### LIST_ARM11="$(boards_by_cpu arm1136) \ imx31_phycore \ imx31_phycore_eet \ mx31pdk \ smdk6400 \ " ######################################################################### ## ARMV7 Systems ######################################################################### LIST_ARMV7="$(boards_by_cpu armv7)" ######################################################################### ## AT91 Systems ######################################################################### LIST_at91="$(boards_by_soc at91)" ######################################################################### ## Xscale Systems ######################################################################### LIST_pxa="$(boards_by_cpu pxa)" LIST_ixp="$(boards_by_cpu ixp) pdnb3 \ scpu \ " ######################################################################### ## ARM groups ######################################################################### LIST_arm=" \ ${LIST_SA} \ ${LIST_ARM9} \ ${LIST_ARM10} \ ${LIST_ARM11} \ ${LIST_ARMV7} \ ${LIST_at91} \ ${LIST_pxa} \ ${LIST_ixp} \ " ######################################################################### ## MIPS Systems (default = big endian) ######################################################################### LIST_mips4kc=" \ incaip \ qemu_mips \ vct_platinum \ vct_platinum_small \ vct_platinum_onenand \ vct_platinum_onenand_small \ vct_platinumavc \ vct_platinumavc_small \ vct_platinumavc_onenand \ vct_platinumavc_onenand_small \ vct_premium \ vct_premium_small \ vct_premium_onenand \ vct_premium_onenand_small \ " LIST_au1xx0=" \ dbau1000 \ dbau1100 \ dbau1500 \ dbau1550 \ gth2 \ " LIST_mips=" \ ${LIST_mips4kc} \ ${LIST_mips5kc} \ ${LIST_au1xx0} \ " ######################################################################### ## MIPS Systems (little endian) ######################################################################### LIST_xburst_el=" \ qi_lb60 \ " LIST_au1xx0_el=" \ dbau1550_el \ pb1000 \ " LIST_mips_el=" \ ${LIST_xburst_el} \ ${LIST_au1xx0_el} \ " ######################################################################### ## x86 Systems ######################################################################### LIST_x86="$(boards_by_arch x86)" ######################################################################### ## Nios-II Systems ######################################################################### LIST_nios2="$(boards_by_arch nios2)" ######################################################################### ## MicroBlaze Systems ######################################################################### LIST_microblaze="$(boards_by_arch microblaze)" ######################################################################### ## ColdFire Systems ######################################################################### LIST_m68k="$(boards_by_arch m68k) EB+MCF-EV123 \ EB+MCF-EV123_internal \ M52277EVB \ M5235EVB \ M54451EVB \ M54455EVB \ " LIST_coldfire=${LIST_m68k} ######################################################################### ## AVR32 Systems ######################################################################### LIST_avr32="$(boards_by_arch avr32)" ######################################################################### ## Blackfin Systems ######################################################################### LIST_blackfin="$(boards_by_arch blackfin)" ######################################################################### ## SH Systems ######################################################################### LIST_sh2="$(boards_by_cpu sh2)" LIST_sh3="$(boards_by_cpu sh3)" LIST_sh4="$(boards_by_cpu sh4)" LIST_sh="$(boards_by_arch sh)" ######################################################################### ## SPARC Systems ######################################################################### LIST_sparc="$(boards_by_arch sparc)" ######################################################################### ## NDS32 Systems ######################################################################### LIST_nds32="$(boards_by_arch nds32)" #----------------------------------------------------------------------- build_target() { target=$1 if [ "$ONLY_LIST" == 'y' ] ; then echo "$target" return fi ${MAKE} distclean >/dev/null ${MAKE} -s ${target}_config ${MAKE} ${JOBS} all 2>&1 >${LOG_DIR}/$target.MAKELOG \ | tee ${LOG_DIR}/$target.ERR # Check for 'make' errors if [ ${PIPESTATUS[0]} -ne 0 ] ; then RC=1 fi if [ -s ${LOG_DIR}/$target.ERR ] ; then ERR_CNT=$((ERR_CNT + 1)) ERR_LIST="${ERR_LIST} $target" else rm ${LOG_DIR}/$target.ERR fi TOTAL_CNT=$((TOTAL_CNT + 1)) ${CROSS_COMPILE}size ${BUILD_DIR}/u-boot \ | tee -a ${LOG_DIR}/$target.MAKELOG } build_targets() { for t in "$@" ; do # If a LIST_xxx var exists, use it. But avoid variable # expansion in the eval when a board name contains certain # characters that the shell interprets. case ${t} in *[-+=]*) list= ;; *) list=$(eval echo '${LIST_'$t'}') ;; esac if [ -n "${list}" ] ; then build_targets ${list} else build_target ${t} fi done } #----------------------------------------------------------------------- print_stats() { if [ "$ONLY_LIST" == 'y' ] ; then return ; fi echo "" echo "--------------------- SUMMARY ----------------------------" echo "Boards compiled: ${TOTAL_CNT}" if [ ${ERR_CNT} -gt 0 ] ; then echo "Boards with warnings or errors: ${ERR_CNT} (${ERR_LIST} )" fi echo "----------------------------------------------------------" exit $RC } #----------------------------------------------------------------------- # Build target groups selected by options, plus any command line args set -- ${SELECTED} "$@" # run PowerPC by default [ $# = 0 ] && set -- powerpc build_targets "$@"
1001-study-uboot
MAKEALL
Shell
gpl3
14,499
#!/bin/sh usage() { ( echo "Usage: $0 [board IP] [board port]" echo "" echo "If IP is not specified, 'localhost' will be used" echo "If port is not specified, '2001' will be used" [ -z "$*" ] && exit 0 echo "" echo "ERROR: $*" exit 1 ) 1>&2 exit $? } while [ -n "$1" ] ; do case $1 in -h|--help) usage;; --) break;; -*) usage "Invalid option $1";; *) break;; esac shift done ip=${1:-localhost} port=${2:-2001} if [ -z "${ip}" ] || [ -n "$3" ] ; then usage "Invalid number of arguments" fi trap "stty icanon echo opost intr ^C" 0 2 3 5 10 13 15 echo "NOTE: the interrupt signal (normally ^C) has been remapped to ^T" stty -icanon -echo -opost intr ^T nc ${ip} ${port} exit 0
1001-study-uboot
tools/jtagconsole
Shell
gpl3
725
/* * (C) Copyright 2008 Semihalf * * (C) Copyright 2000-2009 * DENX Software Engineering * Wolfgang Denk, wd@denx.de * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include "mkimage.h" #include <image.h> #include <version.h> static void copy_file(int, const char *, int); static void usage(void); /* image_type_params link list to maintain registered image type supports */ struct image_type_params *mkimage_tparams = NULL; /* parameters initialized by core will be used by the image type code */ struct mkimage_params params = { .os = IH_OS_LINUX, .arch = IH_ARCH_PPC, .type = IH_TYPE_KERNEL, .comp = IH_COMP_GZIP, .dtc = MKIMAGE_DEFAULT_DTC_OPTIONS, .imagename = "", }; /* * mkimage_register - * * It is used to register respective image generation/list support to the * mkimage core * * the input struct image_type_params is checked and appended to the link * list, if the input structure is already registered, error */ void mkimage_register (struct image_type_params *tparams) { struct image_type_params **tp; if (!tparams) { fprintf (stderr, "%s: %s: Null input\n", params.cmdname, __FUNCTION__); exit (EXIT_FAILURE); } /* scan the linked list, check for registry and point the last one */ for (tp = &mkimage_tparams; *tp != NULL; tp = &(*tp)->next) { if (!strcmp((*tp)->name, tparams->name)) { fprintf (stderr, "%s: %s already registered\n", params.cmdname, tparams->name); return; } } /* add input struct entry at the end of link list */ *tp = tparams; /* mark input entry as last entry in the link list */ tparams->next = NULL; debug ("Registered %s\n", tparams->name); } /* * mkimage_get_type - * * It scans all registers image type supports * checks the input type_id for each supported image type * * if successful, * returns respective image_type_params pointer if success * if input type_id is not supported by any of image_type_support * returns NULL */ struct image_type_params *mkimage_get_type(int type) { struct image_type_params *curr; for (curr = mkimage_tparams; curr != NULL; curr = curr->next) { if (curr->check_image_type) { if (!curr->check_image_type (type)) return curr; } } return NULL; } /* * mkimage_verify_print_header - * * It scans mkimage_tparams link list, * verifies image_header for each supported image type * if verification is successful, prints respective header * * returns negative if input image format does not match with any of * supported image types */ int mkimage_verify_print_header (void *ptr, struct stat *sbuf) { int retval = -1; struct image_type_params *curr; for (curr = mkimage_tparams; curr != NULL; curr = curr->next ) { if (curr->verify_header) { retval = curr->verify_header ( (unsigned char *)ptr, sbuf->st_size, &params); if (retval == 0) { /* * Print the image information * if verify is successful */ if (curr->print_header) curr->print_header (ptr); else { fprintf (stderr, "%s: print_header undefined for %s\n", params.cmdname, curr->name); } break; } } } return retval; } int main (int argc, char **argv) { int ifd = -1; struct stat sbuf; char *ptr; int retval = 0; struct image_type_params *tparams = NULL; /* Init Kirkwood Boot image generation/list support */ init_kwb_image_type (); /* Init Freescale imx Boot image generation/list support */ init_imx_image_type (); /* Init FIT image generation/list support */ init_fit_image_type (); /* Init TI OMAP Boot image generation/list support */ init_omap_image_type(); /* Init Default image generation/list support */ init_default_image_type (); /* Init Davinci UBL support */ init_ubl_image_type(); /* Init Davinci AIS support */ init_ais_image_type(); params.cmdname = *argv; params.addr = params.ep = 0; while (--argc > 0 && **++argv == '-') { while (*++*argv) { switch (**argv) { case 'l': params.lflag = 1; break; case 'A': if ((--argc <= 0) || (params.arch = genimg_get_arch_id (*++argv)) < 0) usage (); goto NXTARG; case 'C': if ((--argc <= 0) || (params.comp = genimg_get_comp_id (*++argv)) < 0) usage (); goto NXTARG; case 'D': if (--argc <= 0) usage (); params.dtc = *++argv; goto NXTARG; case 'O': if ((--argc <= 0) || (params.os = genimg_get_os_id (*++argv)) < 0) usage (); goto NXTARG; case 'T': if ((--argc <= 0) || (params.type = genimg_get_type_id (*++argv)) < 0) usage (); goto NXTARG; case 'a': if (--argc <= 0) usage (); params.addr = strtoul (*++argv, &ptr, 16); if (*ptr) { fprintf (stderr, "%s: invalid load address %s\n", params.cmdname, *argv); exit (EXIT_FAILURE); } goto NXTARG; case 'd': if (--argc <= 0) usage (); params.datafile = *++argv; params.dflag = 1; goto NXTARG; case 'e': if (--argc <= 0) usage (); params.ep = strtoul (*++argv, &ptr, 16); if (*ptr) { fprintf (stderr, "%s: invalid entry point %s\n", params.cmdname, *argv); exit (EXIT_FAILURE); } params.eflag = 1; goto NXTARG; case 'f': if (--argc <= 0) usage (); /* * The flattened image tree (FIT) format * requires a flattened device tree image type */ params.type = IH_TYPE_FLATDT; params.datafile = *++argv; params.fflag = 1; goto NXTARG; case 'n': if (--argc <= 0) usage (); params.imagename = *++argv; goto NXTARG; case 's': params.skipcpy = 1; break; case 'v': params.vflag++; break; case 'V': printf("mkimage version %s\n", PLAIN_VERSION); exit(EXIT_SUCCESS); case 'x': params.xflag++; break; default: usage (); } } NXTARG: ; } if (argc != 1) usage (); /* set tparams as per input type_id */ tparams = mkimage_get_type(params.type); if (tparams == NULL) { fprintf (stderr, "%s: unsupported type %s\n", params.cmdname, genimg_get_type_name(params.type)); exit (EXIT_FAILURE); } /* * check the passed arguments parameters meets the requirements * as per image type to be generated/listed */ if (tparams->check_params) if (tparams->check_params (&params)) usage (); if (!params.eflag) { params.ep = params.addr; /* If XIP, entry point must be after the U-Boot header */ if (params.xflag) params.ep += tparams->header_size; } params.imagefile = *argv; if (params.fflag){ if (tparams->fflag_handle) /* * in some cases, some additional processing needs * to be done if fflag is defined * * For ex. fit_handle_file for Fit file support */ retval = tparams->fflag_handle(&params); if (retval != EXIT_SUCCESS) exit (retval); } if (params.lflag || params.fflag) { ifd = open (params.imagefile, O_RDONLY|O_BINARY); } else { ifd = open (params.imagefile, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, 0666); } if (ifd < 0) { fprintf (stderr, "%s: Can't open %s: %s\n", params.cmdname, params.imagefile, strerror(errno)); exit (EXIT_FAILURE); } if (params.lflag || params.fflag) { /* * list header information of existing image */ if (fstat(ifd, &sbuf) < 0) { fprintf (stderr, "%s: Can't stat %s: %s\n", params.cmdname, params.imagefile, strerror(errno)); exit (EXIT_FAILURE); } if ((unsigned)sbuf.st_size < tparams->header_size) { fprintf (stderr, "%s: Bad size: \"%s\" is not valid image\n", params.cmdname, params.imagefile); exit (EXIT_FAILURE); } ptr = mmap(0, sbuf.st_size, PROT_READ, MAP_SHARED, ifd, 0); if (ptr == MAP_FAILED) { fprintf (stderr, "%s: Can't read %s: %s\n", params.cmdname, params.imagefile, strerror(errno)); exit (EXIT_FAILURE); } /* * scan through mkimage registry for all supported image types * and verify the input image file header for match * Print the image information for matched image type * Returns the error code if not matched */ retval = mkimage_verify_print_header (ptr, &sbuf); (void) munmap((void *)ptr, sbuf.st_size); (void) close (ifd); exit (retval); } /* * In case there an header with a variable * length will be added, the corresponding * function is called. This is responsible to * allocate memory for the header itself. */ if (tparams->vrec_header) tparams->vrec_header(&params, tparams); else memset(tparams->hdr, 0, tparams->header_size); if (write(ifd, tparams->hdr, tparams->header_size) != tparams->header_size) { fprintf (stderr, "%s: Write error on %s: %s\n", params.cmdname, params.imagefile, strerror(errno)); exit (EXIT_FAILURE); } if (!params.skipcpy && (params.type == IH_TYPE_MULTI || params.type == IH_TYPE_SCRIPT)) { char *file = params.datafile; uint32_t size; for (;;) { char *sep = NULL; if (file) { if ((sep = strchr(file, ':')) != NULL) { *sep = '\0'; } if (stat (file, &sbuf) < 0) { fprintf (stderr, "%s: Can't stat %s: %s\n", params.cmdname, file, strerror(errno)); exit (EXIT_FAILURE); } size = cpu_to_uimage (sbuf.st_size); } else { size = 0; } if (write(ifd, (char *)&size, sizeof(size)) != sizeof(size)) { fprintf (stderr, "%s: Write error on %s: %s\n", params.cmdname, params.imagefile, strerror(errno)); exit (EXIT_FAILURE); } if (!file) { break; } if (sep) { *sep = ':'; file = sep + 1; } else { file = NULL; } } file = params.datafile; for (;;) { char *sep = strchr(file, ':'); if (sep) { *sep = '\0'; copy_file (ifd, file, 1); *sep++ = ':'; file = sep; } else { copy_file (ifd, file, 0); break; } } } else { copy_file (ifd, params.datafile, 0); } /* We're a bit of paranoid */ #if defined(_POSIX_SYNCHRONIZED_IO) && \ !defined(__sun__) && \ !defined(__FreeBSD__) && \ !defined(__APPLE__) (void) fdatasync (ifd); #else (void) fsync (ifd); #endif if (fstat(ifd, &sbuf) < 0) { fprintf (stderr, "%s: Can't stat %s: %s\n", params.cmdname, params.imagefile, strerror(errno)); exit (EXIT_FAILURE); } ptr = mmap(0, sbuf.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, ifd, 0); if (ptr == MAP_FAILED) { fprintf (stderr, "%s: Can't map %s: %s\n", params.cmdname, params.imagefile, strerror(errno)); exit (EXIT_FAILURE); } /* Setup the image header as per input image type*/ if (tparams->set_header) tparams->set_header (ptr, &sbuf, ifd, &params); else { fprintf (stderr, "%s: Can't set header for %s: %s\n", params.cmdname, tparams->name, strerror(errno)); exit (EXIT_FAILURE); } /* Print the image information by processing image header */ if (tparams->print_header) tparams->print_header (ptr); else { fprintf (stderr, "%s: Can't print header for %s: %s\n", params.cmdname, tparams->name, strerror(errno)); exit (EXIT_FAILURE); } (void) munmap((void *)ptr, sbuf.st_size); /* We're a bit of paranoid */ #if defined(_POSIX_SYNCHRONIZED_IO) && \ !defined(__sun__) && \ !defined(__FreeBSD__) && \ !defined(__APPLE__) (void) fdatasync (ifd); #else (void) fsync (ifd); #endif if (close(ifd)) { fprintf (stderr, "%s: Write error on %s: %s\n", params.cmdname, params.imagefile, strerror(errno)); exit (EXIT_FAILURE); } exit (EXIT_SUCCESS); } static void copy_file (int ifd, const char *datafile, int pad) { int dfd; struct stat sbuf; unsigned char *ptr; int tail; int zero = 0; int offset = 0; int size; struct image_type_params *tparams = mkimage_get_type (params.type); if (params.vflag) { fprintf (stderr, "Adding Image %s\n", datafile); } if ((dfd = open(datafile, O_RDONLY|O_BINARY)) < 0) { fprintf (stderr, "%s: Can't open %s: %s\n", params.cmdname, datafile, strerror(errno)); exit (EXIT_FAILURE); } if (fstat(dfd, &sbuf) < 0) { fprintf (stderr, "%s: Can't stat %s: %s\n", params.cmdname, datafile, strerror(errno)); exit (EXIT_FAILURE); } ptr = mmap(0, sbuf.st_size, PROT_READ, MAP_SHARED, dfd, 0); if (ptr == MAP_FAILED) { fprintf (stderr, "%s: Can't read %s: %s\n", params.cmdname, datafile, strerror(errno)); exit (EXIT_FAILURE); } if (params.xflag) { unsigned char *p = NULL; /* * XIP: do not append the image_header_t at the * beginning of the file, but consume the space * reserved for it. */ if ((unsigned)sbuf.st_size < tparams->header_size) { fprintf (stderr, "%s: Bad size: \"%s\" is too small for XIP\n", params.cmdname, datafile); exit (EXIT_FAILURE); } for (p = ptr; p < ptr + tparams->header_size; p++) { if ( *p != 0xff ) { fprintf (stderr, "%s: Bad file: \"%s\" has invalid buffer for XIP\n", params.cmdname, datafile); exit (EXIT_FAILURE); } } offset = tparams->header_size; } size = sbuf.st_size - offset; if (write(ifd, ptr + offset, size) != size) { fprintf (stderr, "%s: Write error on %s: %s\n", params.cmdname, params.imagefile, strerror(errno)); exit (EXIT_FAILURE); } if (pad && ((tail = size % 4) != 0)) { if (write(ifd, (char *)&zero, 4-tail) != 4-tail) { fprintf (stderr, "%s: Write error on %s: %s\n", params.cmdname, params.imagefile, strerror(errno)); exit (EXIT_FAILURE); } } (void) munmap((void *)ptr, sbuf.st_size); (void) close (dfd); } void usage () { fprintf (stderr, "Usage: %s -l image\n" " -l ==> list image header information\n", params.cmdname); fprintf (stderr, " %s [-x] -A arch -O os -T type -C comp " "-a addr -e ep -n name -d data_file[:data_file...] image\n" " -A ==> set architecture to 'arch'\n" " -O ==> set operating system to 'os'\n" " -T ==> set image type to 'type'\n" " -C ==> set compression type 'comp'\n" " -a ==> set load address to 'addr' (hex)\n" " -e ==> set entry point to 'ep' (hex)\n" " -n ==> set image name to 'name'\n" " -d ==> use image data from 'datafile'\n" " -x ==> set XIP (execute in place)\n", params.cmdname); fprintf (stderr, " %s [-D dtc_options] -f fit-image.its fit-image\n", params.cmdname); fprintf (stderr, " %s -V ==> print version information and exit\n", params.cmdname); exit (EXIT_FAILURE); }
1001-study-uboot
tools/mkimage.c
C
gpl3
15,043
/* * (C) Copyright 2001 * Murray Jensen <Murray.Jensen@cmst.csiro.au> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <time.h> int main(int argc, char *argv[]) { unsigned long ethaddr_low, ethaddr_high; srand(time(0) | getpid()); /* * setting the 2nd LSB in the most significant byte of * the address makes it a locally administered ethernet * address */ ethaddr_high = (rand() & 0xfeff) | 0x0200; ethaddr_low = rand(); printf("%02lx:%02lx:%02lx:%02lx:%02lx:%02lx\n", ethaddr_high >> 8, ethaddr_high & 0xff, ethaddr_low >> 24, (ethaddr_low >> 16) & 0xff, (ethaddr_low >> 8) & 0xff, ethaddr_low & 0xff); return (0); }
1001-study-uboot
tools/gen_eth_addr.c
C
gpl3
1,495
/* * (C) Copyright 2009 * Stefano Babic, DENX Software Engineering, sbabic@denx.de. * * (C) Copyright 2008 * Marvell Semiconductor <www.marvell.com> * Written-by: Prafulla Wadaskar <prafulla@marvell.com> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ /* Required to obtain the getline prototype from stdio.h */ #define _GNU_SOURCE #include "mkimage.h" #include <image.h> #include "imximage.h" /* * Supported commands for configuration file */ static table_entry_t imximage_cmds[] = { {CMD_BOOT_FROM, "BOOT_FROM", "boot command", }, {CMD_DATA, "DATA", "Reg Write Data", }, {CMD_IMAGE_VERSION, "IMAGE_VERSION", "image version", }, {-1, "", "", }, }; /* * Supported Boot options for configuration file * this is needed to set the correct flash offset */ static table_entry_t imximage_bootops[] = { {FLASH_OFFSET_SPI, "spi", "SPI Flash", }, {FLASH_OFFSET_NAND, "nand", "NAND Flash", }, {FLASH_OFFSET_SD, "sd", "SD Card", }, {FLASH_OFFSET_ONENAND, "onenand", "OneNAND Flash",}, {-1, "", "Invalid", }, }; /* * IMXIMAGE version definition for i.MX chips */ static table_entry_t imximage_versions[] = { {IMXIMAGE_V1, "", " (i.MX25/35/51 compatible)", }, {IMXIMAGE_V2, "", " (i.MX53 compatible)", }, {-1, "", " (Invalid)", }, }; static struct imx_header imximage_header; static uint32_t imximage_version; static set_dcd_val_t set_dcd_val; static set_dcd_rst_t set_dcd_rst; static set_imx_hdr_t set_imx_hdr; static uint32_t get_cfg_value(char *token, char *name, int linenr) { char *endptr; uint32_t value; errno = 0; value = strtoul(token, &endptr, 16); if (errno || (token == endptr)) { fprintf(stderr, "Error: %s[%d] - Invalid hex data(%s)\n", name, linenr, token); exit(EXIT_FAILURE); } return value; } static uint32_t detect_imximage_version(struct imx_header *imx_hdr) { imx_header_v1_t *hdr_v1 = &imx_hdr->header.hdr_v1; imx_header_v2_t *hdr_v2 = &imx_hdr->header.hdr_v2; flash_header_v1_t *fhdr_v1 = &hdr_v1->fhdr; flash_header_v2_t *fhdr_v2 = &hdr_v2->fhdr; /* Try to detect V1 */ if ((fhdr_v1->app_code_barker == APP_CODE_BARKER) && (hdr_v1->dcd_table.preamble.barker == DCD_BARKER)) return IMXIMAGE_V1; /* Try to detect V2 */ if ((fhdr_v2->header.tag == IVT_HEADER_TAG) && (hdr_v2->dcd_table.header.tag == DCD_HEADER_TAG)) return IMXIMAGE_V2; return IMXIMAGE_VER_INVALID; } static void err_imximage_version(int version) { fprintf(stderr, "Error: Unsupported imximage version:%d\n", version); exit(EXIT_FAILURE); } static void set_dcd_val_v1(struct imx_header *imxhdr, char *name, int lineno, int fld, uint32_t value, uint32_t off) { dcd_v1_t *dcd_v1 = &imxhdr->header.hdr_v1.dcd_table; switch (fld) { case CFG_REG_SIZE: /* Byte, halfword, word */ if ((value != 1) && (value != 2) && (value != 4)) { fprintf(stderr, "Error: %s[%d] - " "Invalid register size " "(%d)\n", name, lineno, value); exit(EXIT_FAILURE); } dcd_v1->addr_data[off].type = value; break; case CFG_REG_ADDRESS: dcd_v1->addr_data[off].addr = value; break; case CFG_REG_VALUE: dcd_v1->addr_data[off].value = value; break; default: break; } } static void set_dcd_val_v2(struct imx_header *imxhdr, char *name, int lineno, int fld, uint32_t value, uint32_t off) { dcd_v2_t *dcd_v2 = &imxhdr->header.hdr_v2.dcd_table; switch (fld) { case CFG_REG_ADDRESS: dcd_v2->addr_data[off].addr = cpu_to_be32(value); break; case CFG_REG_VALUE: dcd_v2->addr_data[off].value = cpu_to_be32(value); break; default: break; } } /* * Complete setting up the rest field of DCD of V1 * such as barker code and DCD data length. */ static void set_dcd_rst_v1(struct imx_header *imxhdr, uint32_t dcd_len, char *name, int lineno) { dcd_v1_t *dcd_v1 = &imxhdr->header.hdr_v1.dcd_table; if (dcd_len > MAX_HW_CFG_SIZE_V1) { fprintf(stderr, "Error: %s[%d] -" "DCD table exceeds maximum size(%d)\n", name, lineno, MAX_HW_CFG_SIZE_V1); exit(EXIT_FAILURE); } dcd_v1->preamble.barker = DCD_BARKER; dcd_v1->preamble.length = dcd_len * sizeof(dcd_type_addr_data_t); } /* * Complete setting up the reset field of DCD of V2 * such as DCD tag, version, length, etc. */ static void set_dcd_rst_v2(struct imx_header *imxhdr, uint32_t dcd_len, char *name, int lineno) { dcd_v2_t *dcd_v2 = &imxhdr->header.hdr_v2.dcd_table; if (dcd_len > MAX_HW_CFG_SIZE_V2) { fprintf(stderr, "Error: %s[%d] -" "DCD table exceeds maximum size(%d)\n", name, lineno, MAX_HW_CFG_SIZE_V2); exit(EXIT_FAILURE); } dcd_v2->header.tag = DCD_HEADER_TAG; dcd_v2->header.length = cpu_to_be16( dcd_len * sizeof(dcd_addr_data_t) + 8); dcd_v2->header.version = DCD_VERSION; dcd_v2->write_dcd_command.tag = DCD_COMMAND_TAG; dcd_v2->write_dcd_command.length = cpu_to_be16( dcd_len * sizeof(dcd_addr_data_t) + 4); dcd_v2->write_dcd_command.param = DCD_COMMAND_PARAM; } static void set_imx_hdr_v1(struct imx_header *imxhdr, uint32_t dcd_len, struct stat *sbuf, struct mkimage_params *params) { imx_header_v1_t *hdr_v1 = &imxhdr->header.hdr_v1; flash_header_v1_t *fhdr_v1 = &hdr_v1->fhdr; dcd_v1_t *dcd_v1 = &hdr_v1->dcd_table; uint32_t base_offset; /* Set default offset */ imxhdr->flash_offset = FLASH_OFFSET_STANDARD; /* Set magic number */ fhdr_v1->app_code_barker = APP_CODE_BARKER; fhdr_v1->app_dest_ptr = params->addr; fhdr_v1->app_dest_ptr = params->ep - imxhdr->flash_offset - sizeof(struct imx_header); fhdr_v1->app_code_jump_vector = params->ep; base_offset = fhdr_v1->app_dest_ptr + imxhdr->flash_offset ; fhdr_v1->dcd_ptr_ptr = (uint32_t) (offsetof(flash_header_v1_t, dcd_ptr) - offsetof(flash_header_v1_t, app_code_jump_vector) + base_offset); fhdr_v1->dcd_ptr = base_offset + offsetof(imx_header_v1_t, dcd_table); /* The external flash header must be at the end of the DCD table */ dcd_v1->addr_data[dcd_len].type = sbuf->st_size + imxhdr->flash_offset + sizeof(struct imx_header); /* Security feature are not supported */ fhdr_v1->app_code_csf = 0; fhdr_v1->super_root_key = 0; } static void set_imx_hdr_v2(struct imx_header *imxhdr, uint32_t dcd_len, struct stat *sbuf, struct mkimage_params *params) { imx_header_v2_t *hdr_v2 = &imxhdr->header.hdr_v2; flash_header_v2_t *fhdr_v2 = &hdr_v2->fhdr; /* Set default offset */ imxhdr->flash_offset = FLASH_OFFSET_STANDARD; /* Set magic number */ fhdr_v2->header.tag = IVT_HEADER_TAG; /* 0xD1 */ fhdr_v2->header.length = cpu_to_be16(sizeof(flash_header_v2_t)); fhdr_v2->header.version = IVT_VERSION; /* 0x40 */ fhdr_v2->entry = params->ep; fhdr_v2->reserved1 = fhdr_v2->reserved2 = 0; fhdr_v2->self = params->ep - sizeof(struct imx_header); fhdr_v2->dcd_ptr = fhdr_v2->self + offsetof(imx_header_v2_t, dcd_table); fhdr_v2->boot_data_ptr = fhdr_v2->self + offsetof(imx_header_v2_t, boot_data); hdr_v2->boot_data.start = fhdr_v2->self - imxhdr->flash_offset; hdr_v2->boot_data.size = sbuf->st_size + imxhdr->flash_offset + sizeof(struct imx_header); /* Security feature are not supported */ fhdr_v2->csf = 0; } static void set_hdr_func(struct imx_header *imxhdr) { switch (imximage_version) { case IMXIMAGE_V1: set_dcd_val = set_dcd_val_v1; set_dcd_rst = set_dcd_rst_v1; set_imx_hdr = set_imx_hdr_v1; break; case IMXIMAGE_V2: set_dcd_val = set_dcd_val_v2; set_dcd_rst = set_dcd_rst_v2; set_imx_hdr = set_imx_hdr_v2; break; default: err_imximage_version(imximage_version); break; } } static void print_hdr_v1(struct imx_header *imx_hdr) { imx_header_v1_t *hdr_v1 = &imx_hdr->header.hdr_v1; flash_header_v1_t *fhdr_v1 = &hdr_v1->fhdr; dcd_v1_t *dcd_v1 = &hdr_v1->dcd_table; uint32_t size, length, ver; size = dcd_v1->preamble.length; if (size > (MAX_HW_CFG_SIZE_V1 * sizeof(dcd_type_addr_data_t))) { fprintf(stderr, "Error: Image corrupt DCD size %d exceed maximum %d\n", (uint32_t)(size / sizeof(dcd_type_addr_data_t)), MAX_HW_CFG_SIZE_V1); exit(EXIT_FAILURE); } length = dcd_v1->preamble.length / sizeof(dcd_type_addr_data_t); ver = detect_imximage_version(imx_hdr); printf("Image Type: Freescale IMX Boot Image\n"); printf("Image Ver: %x", ver); printf("%s\n", get_table_entry_name(imximage_versions, NULL, ver)); printf("Data Size: "); genimg_print_size(dcd_v1->addr_data[length].type); printf("Load Address: %08x\n", (uint32_t)fhdr_v1->app_dest_ptr); printf("Entry Point: %08x\n", (uint32_t)fhdr_v1->app_code_jump_vector); } static void print_hdr_v2(struct imx_header *imx_hdr) { imx_header_v2_t *hdr_v2 = &imx_hdr->header.hdr_v2; flash_header_v2_t *fhdr_v2 = &hdr_v2->fhdr; dcd_v2_t *dcd_v2 = &hdr_v2->dcd_table; uint32_t size, version; size = be16_to_cpu(dcd_v2->header.length) - 8; if (size > (MAX_HW_CFG_SIZE_V2 * sizeof(dcd_addr_data_t))) { fprintf(stderr, "Error: Image corrupt DCD size %d exceed maximum %d\n", (uint32_t)(size / sizeof(dcd_addr_data_t)), MAX_HW_CFG_SIZE_V2); exit(EXIT_FAILURE); } version = detect_imximage_version(imx_hdr); printf("Image Type: Freescale IMX Boot Image\n"); printf("Image Ver: %x", version); printf("%s\n", get_table_entry_name(imximage_versions, NULL, version)); printf("Data Size: "); genimg_print_size(hdr_v2->boot_data.size); printf("Load Address: %08x\n", (uint32_t)fhdr_v2->boot_data_ptr); printf("Entry Point: %08x\n", (uint32_t)fhdr_v2->entry); } static void parse_cfg_cmd(struct imx_header *imxhdr, int32_t cmd, char *token, char *name, int lineno, int fld, int dcd_len) { int value; static int cmd_ver_first = ~0; switch (cmd) { case CMD_IMAGE_VERSION: imximage_version = get_cfg_value(token, name, lineno); if (cmd_ver_first == 0) { fprintf(stderr, "Error: %s[%d] - IMAGE_VERSION " "command need be the first before other " "valid command in the file\n", name, lineno); exit(EXIT_FAILURE); } cmd_ver_first = 1; set_hdr_func(imxhdr); break; case CMD_BOOT_FROM: imxhdr->flash_offset = get_table_entry_id(imximage_bootops, "imximage boot option", token); if (imxhdr->flash_offset == -1) { fprintf(stderr, "Error: %s[%d] -Invalid boot device" "(%s)\n", name, lineno, token); exit(EXIT_FAILURE); } if (unlikely(cmd_ver_first != 1)) cmd_ver_first = 0; break; case CMD_DATA: value = get_cfg_value(token, name, lineno); (*set_dcd_val)(imxhdr, name, lineno, fld, value, dcd_len); if (unlikely(cmd_ver_first != 1)) cmd_ver_first = 0; break; } } static void parse_cfg_fld(struct imx_header *imxhdr, int32_t *cmd, char *token, char *name, int lineno, int fld, int *dcd_len) { int value; switch (fld) { case CFG_COMMAND: *cmd = get_table_entry_id(imximage_cmds, "imximage commands", token); if (*cmd < 0) { fprintf(stderr, "Error: %s[%d] - Invalid command" "(%s)\n", name, lineno, token); exit(EXIT_FAILURE); } break; case CFG_REG_SIZE: parse_cfg_cmd(imxhdr, *cmd, token, name, lineno, fld, *dcd_len); break; case CFG_REG_ADDRESS: case CFG_REG_VALUE: if (*cmd != CMD_DATA) return; value = get_cfg_value(token, name, lineno); (*set_dcd_val)(imxhdr, name, lineno, fld, value, *dcd_len); if (fld == CFG_REG_VALUE) (*dcd_len)++; break; default: break; } } static uint32_t parse_cfg_file(struct imx_header *imxhdr, char *name) { FILE *fd = NULL; char *line = NULL; char *token, *saveptr1, *saveptr2; int lineno = 0; int fld; size_t len; int dcd_len = 0; int32_t cmd; fd = fopen(name, "r"); if (fd == 0) { fprintf(stderr, "Error: %s - Can't open DCD file\n", name); exit(EXIT_FAILURE); } /* Very simple parsing, line starting with # are comments * and are dropped */ while ((getline(&line, &len, fd)) > 0) { lineno++; token = strtok_r(line, "\r\n", &saveptr1); if (token == NULL) continue; /* Check inside the single line */ for (fld = CFG_COMMAND, cmd = CMD_INVALID, line = token; ; line = NULL, fld++) { token = strtok_r(line, " \t", &saveptr2); if (token == NULL) break; /* Drop all text starting with '#' as comments */ if (token[0] == '#') break; parse_cfg_fld(imxhdr, &cmd, token, name, lineno, fld, &dcd_len); } } (*set_dcd_rst)(imxhdr, dcd_len, name, lineno); fclose(fd); return dcd_len; } static int imximage_check_image_types(uint8_t type) { if (type == IH_TYPE_IMXIMAGE) return EXIT_SUCCESS; else return EXIT_FAILURE; } static int imximage_verify_header(unsigned char *ptr, int image_size, struct mkimage_params *params) { struct imx_header *imx_hdr = (struct imx_header *) ptr; if (detect_imximage_version(imx_hdr) == IMXIMAGE_VER_INVALID) return -FDT_ERR_BADSTRUCTURE; return 0; } static void imximage_print_header(const void *ptr) { struct imx_header *imx_hdr = (struct imx_header *) ptr; uint32_t version = detect_imximage_version(imx_hdr); switch (version) { case IMXIMAGE_V1: print_hdr_v1(imx_hdr); break; case IMXIMAGE_V2: print_hdr_v2(imx_hdr); break; default: err_imximage_version(version); break; } } static void imximage_set_header(void *ptr, struct stat *sbuf, int ifd, struct mkimage_params *params) { struct imx_header *imxhdr = (struct imx_header *)ptr; uint32_t dcd_len; /* * In order to not change the old imx cfg file * by adding VERSION command into it, here need * set up function ptr group to V1 by default. */ imximage_version = IMXIMAGE_V1; set_hdr_func(imxhdr); /* Parse dcd configuration file */ dcd_len = parse_cfg_file(imxhdr, params->imagename); /* Set the imx header */ (*set_imx_hdr)(imxhdr, dcd_len, sbuf, params); } int imximage_check_params(struct mkimage_params *params) { if (!params) return CFG_INVALID; if (!strlen(params->imagename)) { fprintf(stderr, "Error: %s - Configuration file not specified, " "it is needed for imximage generation\n", params->cmdname); return CFG_INVALID; } /* * Check parameters: * XIP is not allowed and verify that incompatible * parameters are not sent at the same time * For example, if list is required a data image must not be provided */ return (params->dflag && (params->fflag || params->lflag)) || (params->fflag && (params->dflag || params->lflag)) || (params->lflag && (params->dflag || params->fflag)) || (params->xflag) || !(strlen(params->imagename)); } /* * imximage parameters */ static struct image_type_params imximage_params = { .name = "Freescale i.MX 5x Boot Image support", .header_size = sizeof(struct imx_header), .hdr = (void *)&imximage_header, .check_image_type = imximage_check_image_types, .verify_header = imximage_verify_header, .print_header = imximage_print_header, .set_header = imximage_set_header, .check_params = imximage_check_params, }; void init_imx_image_type(void) { mkimage_register(&imximage_params); }
1001-study-uboot
tools/imximage.c
C
gpl3
15,663
/* * (C) Copyright 2008 * Marvell Semiconductor <www.marvell.com> * Written-by: Prafulla Wadaskar <prafulla@marvell.com> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #ifndef _KWBIMAGE_H_ #define _KWBIMAGE_H_ #include <stdint.h> #define KWBIMAGE_MAX_CONFIG ((0x1dc - 0x20)/sizeof(struct reg_config)) #define MAX_TEMPBUF_LEN 32 /* NAND ECC Mode */ #define IBR_HDR_ECC_DEFAULT 0x00 #define IBR_HDR_ECC_FORCED_HAMMING 0x01 #define IBR_HDR_ECC_FORCED_RS 0x02 #define IBR_HDR_ECC_DISABLED 0x03 /* Boot Type - block ID */ #define IBR_HDR_I2C_ID 0x4D #define IBR_HDR_SPI_ID 0x5A #define IBR_HDR_NAND_ID 0x8B #define IBR_HDR_SATA_ID 0x78 #define IBR_HDR_PEX_ID 0x9C #define IBR_HDR_UART_ID 0x69 #define IBR_DEF_ATTRIB 0x00 enum kwbimage_cmd { CMD_INVALID, CMD_BOOT_FROM, CMD_NAND_ECC_MODE, CMD_NAND_PAGE_SIZE, CMD_SATA_PIO_MODE, CMD_DDR_INIT_DELAY, CMD_DATA }; enum kwbimage_cmd_types { CFG_INVALID = -1, CFG_COMMAND, CFG_DATA0, CFG_DATA1 }; /* typedefs */ typedef struct bhr_t { uint8_t blockid; /*0 */ uint8_t nandeccmode; /*1 */ uint16_t nandpagesize; /*2-3 */ uint32_t blocksize; /*4-7 */ uint32_t rsvd1; /*8-11 */ uint32_t srcaddr; /*12-15 */ uint32_t destaddr; /*16-19 */ uint32_t execaddr; /*20-23 */ uint8_t satapiomode; /*24 */ uint8_t rsvd3; /*25 */ uint16_t ddrinitdelay; /*26-27 */ uint16_t rsvd2; /*28-29 */ uint8_t ext; /*30 */ uint8_t checkSum; /*31 */ } bhr_t, *pbhr_t; struct reg_config { uint32_t raddr; uint32_t rdata; }; typedef struct extbhr_t { uint32_t dramregsoffs; uint8_t rsrvd1[0x20 - sizeof(uint32_t)]; struct reg_config rcfg[KWBIMAGE_MAX_CONFIG]; uint8_t rsrvd2[7]; uint8_t checkSum; } extbhr_t, *pextbhr_t; struct kwb_header { bhr_t kwb_hdr; extbhr_t kwb_exthdr; }; /* * functions */ void init_kwb_image_type (void); #endif /* _KWBIMAGE_H_ */
1001-study-uboot
tools/kwbimage.h
C
gpl3
2,635
/* * (C) Copyright 2000-2004 * DENX Software Engineering * Wolfgang Denk, wd@denx.de * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #ifndef _MKIIMAGE_H_ #define _MKIIMAGE_H_ #include "os_support.h" #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <time.h> #include <unistd.h> #include <sha1.h> #include "fdt_host.h" #undef MKIMAGE_DEBUG #ifdef MKIMAGE_DEBUG #define debug(fmt,args...) printf (fmt ,##args) #else #define debug(fmt,args...) #endif /* MKIMAGE_DEBUG */ #define MKIMAGE_TMPFILE_SUFFIX ".tmp" #define MKIMAGE_MAX_TMPFILE_LEN 256 #define MKIMAGE_DEFAULT_DTC_OPTIONS "-I dts -O dtb -p 500" #define MKIMAGE_MAX_DTC_CMDLINE_LEN 512 #define MKIMAGE_DTC "dtc" /* assume dtc is in $PATH */ /* * This structure defines all such variables those are initialized by * mkimage main core and need to be referred by image type specific * functions */ struct mkimage_params { int dflag; int eflag; int fflag; int lflag; int vflag; int xflag; int skipcpy; int os; int arch; int type; int comp; char *dtc; unsigned int addr; unsigned int ep; char *imagename; char *datafile; char *imagefile; char *cmdname; }; /* * image type specific variables and callback functions */ struct image_type_params { /* name is an identification tag string for added support */ char *name; /* * header size is local to the specific image type to be supported, * mkimage core treats this as number of bytes */ uint32_t header_size; /* Image type header pointer */ void *hdr; /* * There are several arguments that are passed on the command line * and are registered as flags in mkimage_params structure. * This callback function can be used to check the passed arguments * are in-lined with the image type to be supported * * Returns 1 if parameter check is successful */ int (*check_params) (struct mkimage_params *); /* * This function is used by list command (i.e. mkimage -l <filename>) * image type verification code must be put here * * Returns 0 if image header verification is successful * otherwise, returns respective negative error codes */ int (*verify_header) (unsigned char *, int, struct mkimage_params *); /* Prints image information abstracting from image header */ void (*print_header) (const void *); /* * The header or image contents need to be set as per image type to * be generated using this callback function. * further output file post processing (for ex. checksum calculation, * padding bytes etc..) can also be done in this callback function. */ void (*set_header) (void *, struct stat *, int, struct mkimage_params *); /* * Some image generation support for ex (default image type) supports * more than one type_ids, this callback function is used to check * whether input (-T <image_type>) is supported by registered image * generation/list low level code */ int (*check_image_type) (uint8_t); /* This callback function will be executed if fflag is defined */ int (*fflag_handle) (struct mkimage_params *); /* * This callback function will be executed for variable size record * It is expected to build this header in memory and return its length * and a pointer to it */ int (*vrec_header) (struct mkimage_params *, struct image_type_params *); /* pointer to the next registered entry in linked list */ struct image_type_params *next; }; /* * Exported functions */ void mkimage_register (struct image_type_params *tparams); /* * There is a c file associated with supported image type low level code * for ex. default_image.c, fit_image.c * init is the only function referred by mkimage core. * to avoid a single lined header file, you can define them here * * Supported image types init functions */ void init_ais_image_type(void); void init_kwb_image_type (void); void init_imx_image_type (void); void init_default_image_type (void); void init_fit_image_type (void); void init_ubl_image_type(void); void init_omap_image_type(void); #endif /* _MKIIMAGE_H_ */
1001-study-uboot
tools/mkimage.h
C
gpl3
4,757
/* * (C) Copyright 2007 * Heiko Schocher, DENX Software Engineering, <hs@denx.de> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include "os_support.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <sys/stat.h> #include "sha1.h" int main (int argc, char **argv) { unsigned char output[20]; int i, len; char *imagefile; char *cmdname = *argv; unsigned char *ptr; unsigned char *data; struct stat sbuf; unsigned char *ptroff; int ifd; int off; if (argc > 1) { imagefile = argv[1]; ifd = open (imagefile, O_RDWR|O_BINARY); if (ifd < 0) { fprintf (stderr, "%s: Can't open %s: %s\n", cmdname, imagefile, strerror(errno)); exit (EXIT_FAILURE); } if (fstat (ifd, &sbuf) < 0) { fprintf (stderr, "%s: Can't stat %s: %s\n", cmdname, imagefile, strerror(errno)); exit (EXIT_FAILURE); } len = sbuf.st_size; ptr = (unsigned char *)mmap(0, len, PROT_READ, MAP_SHARED, ifd, 0); if (ptr == (unsigned char *)MAP_FAILED) { fprintf (stderr, "%s: Can't read %s: %s\n", cmdname, imagefile, strerror(errno)); exit (EXIT_FAILURE); } /* create a copy, so we can blank out the sha1 sum */ data = malloc (len); memcpy (data, ptr, len); off = SHA1_SUM_POS; ptroff = &data[len + off]; for (i = 0; i < SHA1_SUM_LEN; i++) { ptroff[i] = 0; } sha1_csum ((unsigned char *) data, len, (unsigned char *)output); printf ("U-Boot sum:\n"); for (i = 0; i < 20 ; i++) { printf ("%02X ", output[i]); } printf ("\n"); /* overwrite the sum in the bin file, with the actual */ lseek (ifd, SHA1_SUM_POS, SEEK_END); if (write (ifd, output, SHA1_SUM_LEN) != SHA1_SUM_LEN) { fprintf (stderr, "%s: Can't write %s: %s\n", cmdname, imagefile, strerror(errno)); exit (EXIT_FAILURE); } free (data); (void) munmap((void *)ptr, len); (void) close (ifd); } return EXIT_SUCCESS; }
1001-study-uboot
tools/ubsha1.c
C
gpl3
2,726
/* bin2header.c - program to convert binary file into a C structure * definition to be included in a header file. * * (C) Copyright 2008 by Harald Welte <laforge@openmoko.org> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <stdlib.h> #include <stdio.h> int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "%s needs one argument: the structure name\n", argv[0]); exit(1); } printf("/* bin2header output - automatically generated */\n"); printf("unsigned char %s[] = {\n", argv[1]); while (1) { int i, nread; unsigned char buf[10]; nread = read(0, buf, sizeof(buf)); if (nread <= 0) break; printf("\t"); for (i = 0; i < nread - 1; i++) printf("0x%02x, ", buf[i]); printf("0x%02x,\n", buf[nread-1]); } printf("};\n"); exit(0); }
1001-study-uboot
tools/bin2header.c
C
gpl3
1,547
/* * Copyright 2008 Extreme Engineering Solutions, Inc. * * mmap/munmap implementation derived from: * Clamav Native Windows Port : mmap win32 compatibility layer * Copyright (c) 2005-2006 Gianluigi Tiesi <sherpya@netfarm.it> * Parts by Kees Zeelenberg <kzlg@users.sourceforge.net> (LibGW32C) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this software; if not, write to the * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "mingw_support.h" #include <stdio.h> #include <stdint.h> #include <string.h> #include <errno.h> #include <assert.h> #include <io.h> int fsync(int fd) { return _commit(fd); } void *mmap(void *addr, size_t len, int prot, int flags, int fd, int offset) { void *map = NULL; HANDLE handle = INVALID_HANDLE_VALUE; DWORD cfm_flags = 0, mvf_flags = 0; switch (prot) { case PROT_READ | PROT_WRITE: cfm_flags = PAGE_READWRITE; mvf_flags = FILE_MAP_ALL_ACCESS; break; case PROT_WRITE: cfm_flags = PAGE_READWRITE; mvf_flags = FILE_MAP_WRITE; break; case PROT_READ: cfm_flags = PAGE_READONLY; mvf_flags = FILE_MAP_READ; break; default: return MAP_FAILED; } handle = CreateFileMappingA((HANDLE) _get_osfhandle(fd), NULL, cfm_flags, HIDWORD(len), LODWORD(len), NULL); if (!handle) return MAP_FAILED; map = MapViewOfFile(handle, mvf_flags, HIDWORD(offset), LODWORD(offset), len); CloseHandle(handle); if (!map) return MAP_FAILED; return map; } int munmap(void *addr, size_t len) { if (!UnmapViewOfFile(addr)) return -1; return 0; } /* Reentrant string tokenizer. Generic version. Copyright (C) 1991,1996-1999,2001,2004,2007 Free Software Foundation, Inc. This file is part of the GNU C Library. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Parse S into tokens separated by characters in DELIM. If S is NULL, the saved pointer in SAVE_PTR is used as the next starting point. For example: char s[] = "-abc-=-def"; char *sp; x = strtok_r(s, "-", &sp); // x = "abc", sp = "=-def" x = strtok_r(NULL, "-=", &sp); // x = "def", sp = NULL x = strtok_r(NULL, "=", &sp); // x = NULL // s = "abc\0-def\0" */ char *strtok_r(char *s, const char *delim, char **save_ptr) { char *token; if (s == NULL) s = *save_ptr; /* Scan leading delimiters. */ s += strspn(s, delim); if (*s == '\0') { *save_ptr = s; return NULL; } /* Find the end of the token. */ token = s; s = strpbrk (token, delim); if (s == NULL) { /* This token finishes the string. */ *save_ptr = memchr(token, '\0', strlen(token)); } else { /* Terminate the token and make *SAVE_PTR point past it. */ *s = '\0'; *save_ptr = s + 1; } return token; } #include "getline.c"
1001-study-uboot
tools/mingw_support.c
C
gpl3
3,924
#include "compiler.h" enum { MODE_GEN_INFO, MODE_GEN_DATA }; typedef struct bitmap_s { /* bitmap description */ uint16_t width; uint16_t height; uint8_t palette[256*3]; uint8_t *data; } bitmap_t; #define DEFAULT_CMAP_SIZE 16 /* size of default color map */ void usage(const char *prog) { fprintf(stderr, "Usage: %s [--gen-info|--gen-data] file\n", prog); } /* * Neutralize little endians. */ uint16_t le_short(uint16_t x) { uint16_t val; uint8_t *p = (uint8_t *)(&x); val = (*p++ & 0xff) << 0; val |= (*p & 0xff) << 8; return val; } void skip_bytes (FILE *fp, int n) { while (n-- > 0) fgetc (fp); } __attribute__ ((__noreturn__)) int error (char * msg, FILE *fp) { fprintf (stderr, "ERROR: %s\n", msg); fclose (fp); exit (EXIT_FAILURE); } void gen_info(bitmap_t *b, uint16_t n_colors) { printf("/*\n" " * Automatically generated by \"tools/bmp_logo\"\n" " *\n" " * DO NOT EDIT\n" " *\n" " */\n\n\n" "#ifndef __BMP_LOGO_H__\n" "#define __BMP_LOGO_H__\n\n" "#define BMP_LOGO_WIDTH\t\t%d\n" "#define BMP_LOGO_HEIGHT\t\t%d\n" "#define BMP_LOGO_COLORS\t\t%d\n" "#define BMP_LOGO_OFFSET\t\t%d\n\n" "extern unsigned short bmp_logo_palette[];\n" "extern unsigned char bmp_logo_bitmap[];\n\n" "#endif /* __BMP_LOGO_H__ */\n", b->width, b->height, n_colors, DEFAULT_CMAP_SIZE); } int main (int argc, char *argv[]) { int mode, i, x; FILE *fp; bitmap_t bmp; bitmap_t *b = &bmp; uint16_t data_offset, n_colors; if (argc < 3) { usage(argv[0]); exit (EXIT_FAILURE); } if (!strcmp(argv[1], "--gen-info")) mode = MODE_GEN_INFO; else if (!strcmp(argv[1], "--gen-data")) mode = MODE_GEN_DATA; else { usage(argv[0]); exit(EXIT_FAILURE); } fp = fopen(argv[2], "rb"); if (!fp) { perror(argv[2]); exit (EXIT_FAILURE); } if (fgetc (fp) != 'B' || fgetc (fp) != 'M') error ("Input file is not a bitmap", fp); /* * read width and height of the image, and the number of colors used; * ignore the rest */ skip_bytes (fp, 8); if (fread (&data_offset, sizeof (uint16_t), 1, fp) != 1) error ("Couldn't read bitmap data offset", fp); skip_bytes (fp, 6); if (fread (&b->width, sizeof (uint16_t), 1, fp) != 1) error ("Couldn't read bitmap width", fp); skip_bytes (fp, 2); if (fread (&b->height, sizeof (uint16_t), 1, fp) != 1) error ("Couldn't read bitmap height", fp); skip_bytes (fp, 22); if (fread (&n_colors, sizeof (uint16_t), 1, fp) != 1) error ("Couldn't read bitmap colors", fp); skip_bytes (fp, 6); /* * Repair endianess. */ data_offset = le_short(data_offset); b->width = le_short(b->width); b->height = le_short(b->height); n_colors = le_short(n_colors); /* assume we are working with an 8-bit file */ if ((n_colors == 0) || (n_colors > 256 - DEFAULT_CMAP_SIZE)) { /* reserve DEFAULT_CMAP_SIZE color map entries for default map */ n_colors = 256 - DEFAULT_CMAP_SIZE; } if (mode == MODE_GEN_INFO) { gen_info(b, n_colors); goto out; } printf("/*\n" " * Automatically generated by \"tools/bmp_logo\"\n" " *\n" " * DO NOT EDIT\n" " *\n" " */\n\n\n" "#ifndef __BMP_LOGO_DATA_H__\n" "#define __BMP_LOGO_DATA_H__\n\n"); /* allocate memory */ if ((b->data = (uint8_t *)malloc(b->width * b->height)) == NULL) error ("Error allocating memory for file", fp); /* read and print the palette information */ printf("unsigned short bmp_logo_palette[] = {\n"); for (i=0; i<n_colors; ++i) { b->palette[(int)(i*3+2)] = fgetc(fp); b->palette[(int)(i*3+1)] = fgetc(fp); b->palette[(int)(i*3+0)] = fgetc(fp); x=fgetc(fp); printf ("%s0x0%X%X%X,%s", ((i%8) == 0) ? "\t" : " ", (b->palette[(int)(i*3+0)] >> 4) & 0x0F, (b->palette[(int)(i*3+1)] >> 4) & 0x0F, (b->palette[(int)(i*3+2)] >> 4) & 0x0F, ((i%8) == 7) ? "\n" : "" ); } /* seek to offset indicated by file header */ fseek(fp, (long)data_offset, SEEK_SET); /* read the bitmap; leave room for default color map */ printf ("\n"); printf ("};\n"); printf ("\n"); printf("unsigned char bmp_logo_bitmap[] = {\n"); for (i=(b->height-1)*b->width; i>=0; i-=b->width) { for (x = 0; x < b->width; x++) { b->data[(uint16_t) i + x] = (uint8_t) fgetc (fp) \ + DEFAULT_CMAP_SIZE; } } for (i=0; i<(b->height*b->width); ++i) { if ((i%8) == 0) putchar ('\t'); printf ("0x%02X,%c", b->data[i], ((i%8) == 7) ? '\n' : ' ' ); } printf ("\n" "};\n\n" "#endif /* __BMP_LOGO_DATA_H__ */\n" ); out: fclose(fp); return 0; }
1001-study-uboot
tools/bmp_logo.c
C
gpl3
4,486
/* * (C) Copyright 2009 Marco Stornelli * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <sys/types.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <unistd.h> #include <asm/page.h> #ifdef MTD_OLD #include <stdint.h> #include <linux/mtd/mtd.h> #else #define __user /* nothing */ #include <mtd/mtd-user.h> #endif #include <sha1.h> #include <fdt.h> #include <libfdt.h> #include <fdt_support.h> #include <image.h> #define MIN(a, b) (((a) < (b)) ? (a) : (b)) extern unsigned long crc32(unsigned long crc, const char *buf, unsigned int len); static void usage(void); static int image_verify_header(char *ptr, int fd); static int flash_bad_block(int fd, uint8_t mtd_type, loff_t start); char *cmdname; char *devicefile; unsigned int sectorcount = 0; int sflag = 0; unsigned int sectoroffset = 0; unsigned int sectorsize = 0; int cflag = 0; int main (int argc, char **argv) { int fd = -1, err = 0, readbyte = 0, j; struct mtd_info_user mtdinfo; char buf[sizeof(image_header_t)]; int found = 0; cmdname = *argv; while (--argc > 0 && **++argv == '-') { while (*++*argv) { switch (**argv) { case 'c': if (--argc <= 0) usage (); sectorcount = (unsigned int)atoi(*++argv); cflag = 1; goto NXTARG; case 'o': if (--argc <= 0) usage (); sectoroffset = (unsigned int)atoi(*++argv); goto NXTARG; case 's': if (--argc <= 0) usage (); sectorsize = (unsigned int)atoi(*++argv); sflag = 1; goto NXTARG; default: usage (); } } NXTARG: ; } if (argc != 1 || cflag == 0 || sflag == 0) usage(); devicefile = *argv; fd = open(devicefile, O_RDONLY); if (fd < 0) { fprintf (stderr, "%s: Can't open %s: %s\n", cmdname, devicefile, strerror(errno)); exit(EXIT_FAILURE); } err = ioctl(fd, MEMGETINFO, &mtdinfo); if (err < 0) { fprintf(stderr, "%s: Cannot get MTD information: %s\n",cmdname, strerror(errno)); exit(EXIT_FAILURE); } if (mtdinfo.type != MTD_NORFLASH && mtdinfo.type != MTD_NANDFLASH) { fprintf(stderr, "%s: Unsupported flash type %u\n", cmdname, mtdinfo.type); exit(EXIT_FAILURE); } if (sectorsize * sectorcount != mtdinfo.size) { fprintf(stderr, "%s: Partition size (%d) incompatible with " "sector size and count\n", cmdname, mtdinfo.size); exit(EXIT_FAILURE); } if (sectorsize * sectoroffset >= mtdinfo.size) { fprintf(stderr, "%s: Partition size (%d) incompatible with " "sector offset given\n", cmdname, mtdinfo.size); exit(EXIT_FAILURE); } if (sectoroffset > sectorcount - 1) { fprintf(stderr, "%s: Sector offset cannot be grater than " "sector count minus one\n", cmdname); exit(EXIT_FAILURE); } printf("Searching....\n"); for (j = sectoroffset; j < sectorcount; ++j) { if (lseek(fd, j*sectorsize, SEEK_SET) != j*sectorsize) { fprintf(stderr, "%s: lseek failure: %s\n", cmdname, strerror(errno)); exit(EXIT_FAILURE); } err = flash_bad_block(fd, mtdinfo.type, j*sectorsize); if (err < 0) exit(EXIT_FAILURE); if (err) continue; /* Skip and jump to next */ readbyte = read(fd, buf, sizeof(image_header_t)); if (readbyte != sizeof(image_header_t)) { fprintf(stderr, "%s: Can't read from device: %s\n", cmdname, strerror(errno)); exit(EXIT_FAILURE); } if (fdt_check_header(buf)) { /* old-style image */ if (image_verify_header(buf, fd)) { found = 1; image_print_contents((image_header_t *)buf); } } else { /* FIT image */ fit_print_contents(buf); } } close(fd); if(!found) printf("No images found\n"); exit(EXIT_SUCCESS); } void usage() { fprintf (stderr, "Usage:\n" " %s [-o offset] -s size -c count device\n" " -o ==> number of sectors to use as offset\n" " -c ==> number of sectors\n" " -s ==> size of sectors (byte)\n", cmdname); exit(EXIT_FAILURE); } static int image_verify_header(char *ptr, int fd) { int len, nread; char *data; uint32_t checksum; image_header_t *hdr = (image_header_t *)ptr; char buf[PAGE_SIZE]; if (image_get_magic(hdr) != IH_MAGIC) return 0; data = (char *)hdr; len = image_get_header_size(); checksum = image_get_hcrc(hdr); hdr->ih_hcrc = htonl(0); /* clear for re-calculation */ if (crc32(0, data, len) != checksum) { fprintf(stderr, "%s: Maybe image found but it has bad header checksum!\n", cmdname); return 0; } len = image_get_size(hdr); checksum = 0; while (len > 0) { nread = read(fd, buf, MIN(len,PAGE_SIZE)); if (nread != MIN(len,PAGE_SIZE)) { fprintf(stderr, "%s: Error while reading: %s\n", cmdname, strerror(errno)); exit(EXIT_FAILURE); } checksum = crc32(checksum, buf, nread); len -= nread; } if (checksum != image_get_dcrc(hdr)) { fprintf (stderr, "%s: Maybe image found but it has corrupted data!\n", cmdname); return 0; } return 1; } /* * Test for bad block on NAND, just returns 0 on NOR, on NAND: * 0 - block is good * > 0 - block is bad * < 0 - failed to test */ static int flash_bad_block(int fd, uint8_t mtd_type, loff_t start) { if (mtd_type == MTD_NANDFLASH) { int badblock = ioctl(fd, MEMGETBADBLOCK, &start); if (badblock < 0) { fprintf(stderr,"%s: Cannot read bad block mark: %s\n", cmdname, strerror(errno)); return badblock; } if (badblock) { return badblock; } } return 0; }
1001-study-uboot
tools/imls/imls.c
C
gpl3
6,160
# # (C) Copyright 2009 Marco Stornelli <marco.stornelli@gmail.com> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # include $(TOPDIR)/config.mk # Generated executable files BIN_FILES-y += imls # Source files which exist outside the tools/imls directory EXT_OBJ_FILES-y += lib/crc32.o EXT_OBJ_FILES-y += lib/md5.o EXT_OBJ_FILES-y += lib/sha1.o EXT_OBJ_FILES-y += common/image.o # Source files located in the tools/imls directory OBJ_FILES-y += imls.o # Flattened device tree objects LIBFDT_OBJ_FILES-y += fdt.o LIBFDT_OBJ_FILES-y += fdt_ro.o LIBFDT_OBJ_FILES-y += fdt_rw.o LIBFDT_OBJ_FILES-y += fdt_strerror.o LIBFDT_OBJ_FILES-y += fdt_wip.o # now $(obj) is defined SRCS += $(addprefix $(SRCTREE)/,$(EXT_OBJ_FILES-y:.o=.c)) SRCS += $(addprefix $(SRCTREE)/tools/,$(OBJ_FILES-y:.o=.c)) SRCS += $(addprefix $(SRCTREE)/lib/libfdt/,$(LIBFDT_OBJ_FILES-y:.o=.c)) BINS := $(addprefix $(obj),$(sort $(BIN_FILES-y))) LIBFDT_OBJS := $(addprefix $(obj),$(LIBFDT_OBJ_FILES-y)) # # Compile for a hosted environment on the target # Define __KERNEL_STRICT_NAMES to prevent typedef overlaps # HOSTCPPFLAGS = -idirafter $(SRCTREE)/include \ -idirafter $(OBJTREE)/include2 \ -idirafter $(OBJTREE)/include \ -I $(SRCTREE)/lib/libfdt \ -I $(SRCTREE)/tools \ -DUSE_HOSTCC -D__KERNEL_STRICT_NAMES ifeq ($(MTD_VERSION),old) HOSTCPPFLAGS += -DMTD_OLD endif all: $(BINS) $(obj)imls: $(obj)imls.o $(obj)crc32.o $(obj)image.o $(obj)md5.o \ $(obj)sha1.o $(LIBFDT_OBJS) $(CC) $(HOSTCFLAGS) $(HOSTLDFLAGS) -o $@ $^ $(STRIP) $@ # Some files complain if compiled with -pedantic, use HOSTCFLAGS_NOPED $(obj)image.o: $(SRCTREE)/common/image.c $(CC) -g $(HOSTCFLAGS_NOPED) -c -o $@ $< $(obj)imls.o: $(SRCTREE)/tools/imls/imls.c $(CC) -g $(HOSTCFLAGS_NOPED) -c -o $@ $< # Some of the tool objects need to be accessed from outside the tools/imls directory $(obj)%.o: $(SRCTREE)/common/%.c $(CC) -g $(HOSTCFLAGS_NOPED) -c -o $@ $< $(obj)%.o: $(SRCTREE)/lib/%.c $(CC) -g $(HOSTCFLAGS) -c -o $@ $< $(obj)%.o: $(SRCTREE)/lib/libfdt/%.c $(CC) -g $(HOSTCFLAGS_NOPED) -c -o $@ $< clean: rm -rf *.o imls ######################################################################### # defines $(obj).depend target include $(SRCTREE)/rules.mk sinclude $(obj).depend #########################################################################
1001-study-uboot
tools/imls/Makefile
Makefile
gpl3
2,990
/************************************************************************* | COPYRIGHT (c) 2000 BY ABATRON AG |************************************************************************* | | PROJECT NAME: Linux Image to S-record Conversion Utility | FILENAME : img2srec.c | | COMPILER : GCC | | TARGET OS : LINUX / UNIX | TARGET HW : - | | PROGRAMMER : Abatron / RD | CREATION : 07.07.00 | |************************************************************************* | | DESCRIPTION : | | Utility to convert a Linux Boot Image to S-record: | ================================================== | | This command line utility can be used to convert a Linux boot image | (zimage.initrd) to S-Record format used for flash programming. | This conversion takes care of the special sections "IMAGE" and INITRD". | | img2srec [-o offset] image > image.srec | | | Build the utility: | ================== | | To build the utility use GCC as follows: | | gcc img2srec.c -o img2srec | | |************************************************************************* | | | UPDATES : | | DATE NAME CHANGES | ----------------------------------------------------------- | Latest update | | 07.07.00 aba Initial release | |*************************************************************************/ /************************************************************************* | INCLUDES |*************************************************************************/ #include "os_support.h" #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <elf.h> #include <unistd.h> #include <errno.h> /************************************************************************* | FUNCTIONS |*************************************************************************/ static char* ExtractHex (uint32_t* value, char* getPtr) { uint32_t num; uint32_t digit; uint8_t c; while (*getPtr == ' ') getPtr++; num = 0; for (;;) { c = *getPtr; if ((c >= '0') && (c <= '9')) digit = (uint32_t)(c - '0'); else if ((c >= 'A') && (c <= 'F')) digit = (uint32_t)(c - 'A' + 10); else if ((c >= 'a') && (c <= 'f')) digit = (uint32_t)(c - 'a' + 10); else break; num <<= 4; num += digit; getPtr++; } /* for */ *value = num; return getPtr; } /* ExtractHex */ static char* ExtractDecimal (uint32_t* value, char* getPtr) { uint32_t num; uint32_t digit; uint8_t c; while (*getPtr == ' ') getPtr++; num = 0; for (;;) { c = *getPtr; if ((c >= '0') && (c <= '9')) digit = (uint32_t)(c - '0'); else break; num *= 10; num += digit; getPtr++; } /* for */ *value = num; return getPtr; } /* ExtractDecimal */ static void ExtractNumber (uint32_t* value, char* getPtr) { bool neg = false;; while (*getPtr == ' ') getPtr++; if (*getPtr == '-') { neg = true; getPtr++; } /* if */ if ((*getPtr == '0') && ((*(getPtr+1) == 'x') || (*(getPtr+1) == 'X'))) { getPtr +=2; (void)ExtractHex(value, getPtr); } /* if */ else { (void)ExtractDecimal(value, getPtr); } /* else */ if (neg) *value = -(*value); } /* ExtractNumber */ static uint8_t* ExtractWord(uint16_t* value, uint8_t* buffer) { uint16_t x; x = (uint16_t)*buffer++; x = (x<<8) + (uint16_t)*buffer++; *value = x; return buffer; } /* ExtractWord */ static uint8_t* ExtractLong(uint32_t* value, uint8_t* buffer) { uint32_t x; x = (uint32_t)*buffer++; x = (x<<8) + (uint32_t)*buffer++; x = (x<<8) + (uint32_t)*buffer++; x = (x<<8) + (uint32_t)*buffer++; *value = x; return buffer; } /* ExtractLong */ static uint8_t* ExtractBlock(uint16_t count, uint8_t* data, uint8_t* buffer) { while (count--) *data++ = *buffer++; return buffer; } /* ExtractBlock */ static char* WriteHex(char* pa, uint8_t value, uint16_t* pCheckSum) { uint16_t temp; static char ByteToHex[] = "0123456789ABCDEF"; *pCheckSum += value; temp = value / 16; *pa++ = ByteToHex[temp]; temp = value % 16; *pa++ = ByteToHex[temp]; return pa; } static char* BuildSRecord(char* pa, uint16_t sType, uint32_t addr, const uint8_t* data, int nCount) { uint16_t addrLen; uint16_t sRLen; uint16_t checkSum; uint16_t i; switch (sType) { case 0: case 1: case 9: addrLen = 2; break; case 2: case 8: addrLen = 3; break; case 3: case 7: addrLen = 4; break; default: return pa; } /* switch */ *pa++ = 'S'; *pa++ = (char)(sType + '0'); sRLen = addrLen + nCount + 1; checkSum = 0; pa = WriteHex(pa, (uint8_t)sRLen, &checkSum); /* Write address field */ for (i = 1; i <= addrLen; i++) { pa = WriteHex(pa, (uint8_t)(addr >> (8 * (addrLen - i))), &checkSum); } /* for */ /* Write code/data fields */ for (i = 0; i < nCount; i++) { pa = WriteHex(pa, *data++, &checkSum); } /* for */ /* Write checksum field */ checkSum = ~checkSum; pa = WriteHex(pa, (uint8_t)checkSum, &checkSum); *pa++ = '\0'; return pa; } static void ConvertELF(char* fileName, uint32_t loadOffset) { FILE* file; int i; int rxCount; uint8_t rxBlock[1024]; uint32_t loadSize; uint32_t firstAddr; uint32_t loadAddr; uint32_t loadDiff = 0; Elf32_Ehdr elfHeader; Elf32_Shdr sectHeader[32]; uint8_t* getPtr; char srecLine[128]; char *hdr_name; /* open file */ if ((file = fopen(fileName,"rb")) == NULL) { fprintf (stderr, "Can't open %s: %s\n", fileName, strerror(errno)); return; } /* if */ /* read ELF header */ rxCount = fread(rxBlock, 1, sizeof elfHeader, file); getPtr = ExtractBlock(sizeof elfHeader.e_ident, elfHeader.e_ident, rxBlock); getPtr = ExtractWord(&elfHeader.e_type, getPtr); getPtr = ExtractWord(&elfHeader.e_machine, getPtr); getPtr = ExtractLong((uint32_t *)&elfHeader.e_version, getPtr); getPtr = ExtractLong((uint32_t *)&elfHeader.e_entry, getPtr); getPtr = ExtractLong((uint32_t *)&elfHeader.e_phoff, getPtr); getPtr = ExtractLong((uint32_t *)&elfHeader.e_shoff, getPtr); getPtr = ExtractLong((uint32_t *)&elfHeader.e_flags, getPtr); getPtr = ExtractWord(&elfHeader.e_ehsize, getPtr); getPtr = ExtractWord(&elfHeader.e_phentsize, getPtr); getPtr = ExtractWord(&elfHeader.e_phnum, getPtr); getPtr = ExtractWord(&elfHeader.e_shentsize, getPtr); getPtr = ExtractWord(&elfHeader.e_shnum, getPtr); getPtr = ExtractWord(&elfHeader.e_shstrndx, getPtr); if ( (rxCount != sizeof elfHeader) || (elfHeader.e_ident[0] != ELFMAG0) || (elfHeader.e_ident[1] != ELFMAG1) || (elfHeader.e_ident[2] != ELFMAG2) || (elfHeader.e_ident[3] != ELFMAG3) || (elfHeader.e_type != ET_EXEC) ) { fclose(file); fprintf (stderr, "*** illegal file format\n"); return; } /* if */ /* read all section headers */ fseek(file, elfHeader.e_shoff, SEEK_SET); for (i = 0; i < elfHeader.e_shnum; i++) { rxCount = fread(rxBlock, 1, sizeof sectHeader[0], file); getPtr = ExtractLong((uint32_t *)&sectHeader[i].sh_name, rxBlock); getPtr = ExtractLong((uint32_t *)&sectHeader[i].sh_type, getPtr); getPtr = ExtractLong((uint32_t *)&sectHeader[i].sh_flags, getPtr); getPtr = ExtractLong((uint32_t *)&sectHeader[i].sh_addr, getPtr); getPtr = ExtractLong((uint32_t *)&sectHeader[i].sh_offset, getPtr); getPtr = ExtractLong((uint32_t *)&sectHeader[i].sh_size, getPtr); getPtr = ExtractLong((uint32_t *)&sectHeader[i].sh_link, getPtr); getPtr = ExtractLong((uint32_t *)&sectHeader[i].sh_info, getPtr); getPtr = ExtractLong((uint32_t *)&sectHeader[i].sh_addralign, getPtr); getPtr = ExtractLong((uint32_t *)&sectHeader[i].sh_entsize, getPtr); if (rxCount != sizeof sectHeader[0]) { fclose(file); fprintf (stderr, "*** illegal file format\n"); return; } /* if */ } /* for */ if ((hdr_name = strrchr(fileName, '/')) == NULL) { hdr_name = fileName; } else { ++hdr_name; } /* write start record */ (void)BuildSRecord(srecLine, 0, 0, (uint8_t *)hdr_name, strlen(hdr_name)); printf("%s\r\n",srecLine); /* write data records */ firstAddr = ~0; loadAddr = 0; for (i = 0; i < elfHeader.e_shnum; i++) { if ( (sectHeader[i].sh_type == SHT_PROGBITS) && (sectHeader[i].sh_size != 0) ) { loadSize = sectHeader[i].sh_size; if (sectHeader[i].sh_flags != 0) { loadAddr = sectHeader[i].sh_addr; loadDiff = loadAddr - sectHeader[i].sh_offset; } /* if */ else { loadAddr = sectHeader[i].sh_offset + loadDiff; } /* else */ if (loadAddr < firstAddr) firstAddr = loadAddr; /* build s-records */ loadSize = sectHeader[i].sh_size; fseek(file, sectHeader[i].sh_offset, SEEK_SET); while (loadSize) { rxCount = fread(rxBlock, 1, (loadSize > 32) ? 32 : loadSize, file); if (rxCount < 0) { fclose(file); fprintf (stderr, "*** illegal file format\n"); return; } /* if */ (void)BuildSRecord(srecLine, 3, loadAddr + loadOffset, rxBlock, rxCount); loadSize -= rxCount; loadAddr += rxCount; printf("%s\r\n",srecLine); } /* while */ } /* if */ } /* for */ /* add end record */ (void)BuildSRecord(srecLine, 7, firstAddr + loadOffset, 0, 0); printf("%s\r\n",srecLine); fclose(file); } /* ConvertELF */ /************************************************************************* | MAIN |*************************************************************************/ int main( int argc, char *argv[ ]) { uint32_t offset; if (argc == 2) { ConvertELF(argv[1], 0); } /* if */ else if ((argc == 4) && (strcmp(argv[1], "-o") == 0)) { ExtractNumber(&offset, argv[2]); ConvertELF(argv[3], offset); } /* if */ else { fprintf (stderr, "Usage: img2srec [-o offset] <image>\n"); } /* if */ return 0; } /* main */
1001-study-uboot
tools/img2srec.c
C
gpl3
9,959
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> int main (int argc, char *argv[]) { int s, len, o, port = 6666; char buf[512]; struct sockaddr_in addr; socklen_t addr_len = sizeof addr; if (argc > 1) port = atoi (argv[1]); s = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP); o = 1; len = 4; setsockopt (3, SOL_SOCKET, SO_REUSEADDR, &o, len); addr.sin_family = AF_INET; addr.sin_port = htons (port); addr.sin_addr.s_addr = INADDR_ANY; /* receive broadcasts */ bind (s, (struct sockaddr *) &addr, sizeof addr); for (;;) { len = recvfrom (s, buf, sizeof buf, 0, (struct sockaddr *) &addr, &addr_len); if (len < 0) break; if (write (1, buf, len) != len) fprintf(stderr, "WARNING: serial characters dropped\n"); } return 0; }
1001-study-uboot
tools/ncb.c
C
gpl3
813
/* * (C) Copyright 2011 * Stefano Babic, DENX Software Engineering, sbabic@denx.de. * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ /* Required to obtain the getline prototype from stdio.h */ #define _GNU_SOURCE #include "mkimage.h" #include "aisimage.h" #include <image.h> #define IS_FNC_EXEC(c) (cmd_table[c].AIS_cmd == AIS_CMD_FNLOAD) #define WORD_ALIGN0 4 #define WORD_ALIGN(len) (((len)+WORD_ALIGN0-1) & ~(WORD_ALIGN0-1)) #define MAX_CMD_BUFFER 4096 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) static uint32_t ais_img_size; /* * Supported commands for configuration file */ static table_entry_t aisimage_cmds[] = { {CMD_DATA, "DATA", "Reg Write Data"}, {CMD_FILL, "FILL", "Fill range with pattern"}, {CMD_CRCON, "CRCON", "CRC Enable"}, {CMD_CRCOFF, "CRCOFF", "CRC Disable"}, {CMD_CRCCHECK, "CRCCHECK", "CRC Validate"}, {CMD_JMPCLOSE, "JMPCLOSE", "Jump & Close"}, {CMD_JMP, "JMP", "Jump"}, {CMD_SEQREAD, "SEQREAD", "Sequential read"}, {CMD_PLL0, "PLL0", "PLL0"}, {CMD_PLL1, "PLL1", "PLL1"}, {CMD_CLK, "CLK", "Clock configuration"}, {CMD_DDR2, "DDR2", "DDR2 Configuration"}, {CMD_EMIFA, "EMIFA", "EMIFA"}, {CMD_EMIFA_ASYNC, "EMIFA_ASYNC", "EMIFA Async"}, {CMD_PLL, "PLL", "PLL & Clock configuration"}, {CMD_PSC, "PSC", "PSC setup"}, {CMD_PINMUX, "PINMUX", "Pinmux setup"}, {CMD_BOOTTABLE, "BOOT_TABLE", "Boot table command"}, {-1, "", ""}, }; static struct ais_func_exec { uint32_t index; uint32_t argcnt; } ais_func_table[] = { [CMD_PLL0] = {0, 2}, [CMD_PLL1] = {1, 2}, [CMD_CLK] = {2, 1}, [CMD_DDR2] = {3, 8}, [CMD_EMIFA] = {4, 5}, [CMD_EMIFA_ASYNC] = {5, 5}, [CMD_PLL] = {6, 3}, [CMD_PSC] = {7, 1}, [CMD_PINMUX] = {8, 3} }; static struct cmd_table_t { uint32_t nargs; uint32_t AIS_cmd; } cmd_table[] = { [CMD_FILL] = { 4, AIS_CMD_FILL}, [CMD_CRCON] = { 0, AIS_CMD_ENCRC}, [CMD_CRCOFF] = { 0, AIS_CMD_DISCRC}, [CMD_CRCCHECK] = { 2, AIS_CMD_ENCRC}, [CMD_JMPCLOSE] = { 1, AIS_CMD_JMPCLOSE}, [CMD_JMP] = { 1, AIS_CMD_JMP}, [CMD_SEQREAD] = { 0, AIS_CMD_SEQREAD}, [CMD_PLL0] = { 2, AIS_CMD_FNLOAD}, [CMD_PLL1] = { 2, AIS_CMD_FNLOAD}, [CMD_CLK] = { 1, AIS_CMD_FNLOAD}, [CMD_DDR2] = { 8, AIS_CMD_FNLOAD}, [CMD_EMIFA] = { 5, AIS_CMD_FNLOAD}, [CMD_EMIFA_ASYNC] = { 5, AIS_CMD_FNLOAD}, [CMD_PLL] = { 3, AIS_CMD_FNLOAD}, [CMD_PSC] = { 1, AIS_CMD_FNLOAD}, [CMD_PINMUX] = { 3, AIS_CMD_FNLOAD}, [CMD_BOOTTABLE] = { 4, AIS_CMD_BOOTTBL}, }; static uint32_t get_cfg_value(char *token, char *name, int linenr) { char *endptr; uint32_t value; errno = 0; value = strtoul(token, &endptr, 16); if (errno || (token == endptr)) { fprintf(stderr, "Error: %s[%d] - Invalid hex data(%s)\n", name, linenr, token); exit(EXIT_FAILURE); } return value; } static int get_ais_table_id(uint32_t *ptr) { int i; int func_no; for (i = 0; i < ARRAY_SIZE(cmd_table); i++) { if (*ptr == cmd_table[i].AIS_cmd) { if (cmd_table[i].AIS_cmd != AIS_CMD_FNLOAD) return i; func_no = ((struct ais_cmd_func *)ptr)->func_args & 0xFFFF; if (func_no == ais_func_table[i].index) return i; } } return -1; } static void aisimage_print_header(const void *hdr) { struct ais_header *ais_hdr = (struct ais_header *)hdr; uint32_t *ptr; struct ais_cmd_load *ais_load; int id; if (ais_hdr->magic != AIS_MAGIC_WORD) { fprintf(stderr, "Error: - AIS Magic Number not found\n"); return; } fprintf(stdout, "Image Type: TI Davinci AIS Boot Image\n"); fprintf(stdout, "AIS magic : %08x\n", ais_hdr->magic); ptr = (uint32_t *)&ais_hdr->magic; ptr++; while (*ptr != AIS_CMD_JMPCLOSE) { /* Check if we find the image */ if (*ptr == AIS_CMD_LOAD) { ais_load = (struct ais_cmd_load *)ptr; fprintf(stdout, "Image at : 0x%08x size 0x%08x\n", ais_load->addr, ais_load->size); ptr = ais_load->data + ais_load->size / sizeof(*ptr); continue; } id = get_ais_table_id(ptr); if (id < 0) { fprintf(stderr, "Error: - AIS Image corrupted\n"); return; } fprintf(stdout, "AIS cmd : %s\n", get_table_entry_name(aisimage_cmds, NULL, id)); ptr += cmd_table[id].nargs + IS_FNC_EXEC(id) + 1; if (((void *)ptr - hdr) > ais_img_size) { fprintf(stderr, "AIS Image not terminated by JMPCLOSE\n"); return; } } } static uint32_t *ais_insert_cmd_header(uint32_t cmd, uint32_t nargs, uint32_t *parms, struct image_type_params *tparams, uint32_t *ptr) { int i; *ptr++ = cmd_table[cmd].AIS_cmd; if (IS_FNC_EXEC(cmd)) *ptr++ = ((nargs & 0xFFFF) << 16) + ais_func_table[cmd].index; /* Copy parameters */ for (i = 0; i < nargs; i++) *ptr++ = cpu_to_le32(parms[i]); return ptr; } static uint32_t *ais_alloc_buffer(struct mkimage_params *params) { int dfd; struct stat sbuf; char *datafile = params->datafile; uint32_t *ptr; dfd = open(datafile, O_RDONLY|O_BINARY); if (dfd < 0) { fprintf(stderr, "%s: Can't open %s: %s\n", params->cmdname, datafile, strerror(errno)); exit(EXIT_FAILURE); } if (fstat(dfd, &sbuf) < 0) { fprintf(stderr, "%s: Can't stat %s: %s\n", params->cmdname, datafile, strerror(errno)); exit(EXIT_FAILURE); } /* * Place for header is allocated. The size is taken from * the size of the datafile, that the ais_image_generate() * will copy into the header. Copying the datafile * is not left to the main program, because after the datafile * the header must be terminated with the Jump & Close command. */ ais_img_size = WORD_ALIGN(sbuf.st_size) + MAX_CMD_BUFFER; ptr = (uint32_t *)malloc(WORD_ALIGN(sbuf.st_size) + MAX_CMD_BUFFER); if (!ptr) { fprintf(stderr, "%s: malloc return failure: %s\n", params->cmdname, strerror(errno)); exit(EXIT_FAILURE); } close(dfd); return ptr; } static uint32_t *ais_copy_image(struct mkimage_params *params, uint32_t *aisptr) { int dfd; struct stat sbuf; char *datafile = params->datafile; void *ptr; dfd = open(datafile, O_RDONLY|O_BINARY); if (dfd < 0) { fprintf(stderr, "%s: Can't open %s: %s\n", params->cmdname, datafile, strerror(errno)); exit(EXIT_FAILURE); } if (fstat(dfd, &sbuf) < 0) { fprintf(stderr, "%s: Can't stat %s: %s\n", params->cmdname, datafile, strerror(errno)); exit(EXIT_FAILURE); } ptr = mmap(0, sbuf.st_size, PROT_READ, MAP_SHARED, dfd, 0); *aisptr++ = AIS_CMD_LOAD; *aisptr++ = params->ep; *aisptr++ = sbuf.st_size; memcpy((void *)aisptr, ptr, sbuf.st_size); aisptr += WORD_ALIGN(sbuf.st_size) / sizeof(uint32_t); (void) munmap((void *)ptr, sbuf.st_size); (void) close(dfd); return aisptr; } static int aisimage_generate(struct mkimage_params *params, struct image_type_params *tparams) { FILE *fd = NULL; char *line = NULL; char *token, *saveptr1, *saveptr2; int lineno = 0; int fld; size_t len; int32_t cmd; uint32_t nargs, cmd_parms[10]; uint32_t value, size; char *name = params->imagename; uint32_t *aishdr; fd = fopen(name, "r"); if (fd == 0) { fprintf(stderr, "Error: %s - Can't open AIS configuration\n", name); exit(EXIT_FAILURE); } /* * the size of the header is variable and is computed * scanning the configuration file. */ tparams->header_size = 0; /* * Start allocating a buffer suitable for most command * The buffer is then reallocated if it is too small */ aishdr = ais_alloc_buffer(params); tparams->hdr = aishdr; *aishdr++ = AIS_MAGIC_WORD; /* Very simple parsing, line starting with # are comments * and are dropped */ while ((getline(&line, &len, fd)) > 0) { lineno++; token = strtok_r(line, "\r\n", &saveptr1); if (token == NULL) continue; /* Check inside the single line */ line = token; fld = CFG_COMMAND; cmd = CMD_INVALID; nargs = 0; while (token != NULL) { token = strtok_r(line, " \t", &saveptr2); if (token == NULL) break; /* Drop all text starting with '#' as comments */ if (token[0] == '#') break; switch (fld) { case CFG_COMMAND: cmd = get_table_entry_id(aisimage_cmds, "aisimage commands", token); if (cmd < 0) { fprintf(stderr, "Error: %s[%d] - Invalid command" "(%s)\n", name, lineno, token); exit(EXIT_FAILURE); } break; case CFG_VALUE: value = get_cfg_value(token, name, lineno); cmd_parms[nargs++] = value; if (nargs > cmd_table[cmd].nargs) { fprintf(stderr, "Error: %s[%d] - too much arguments:" "(%s) for command %s\n", name, lineno, token, aisimage_cmds[cmd].sname); exit(EXIT_FAILURE); } break; } line = NULL; fld = CFG_VALUE; } if (cmd != CMD_INVALID) { /* Now insert the command into the header */ aishdr = ais_insert_cmd_header(cmd, nargs, cmd_parms, tparams, aishdr); } } fclose(fd); aishdr = ais_copy_image(params, aishdr); /* Add Jmp & Close */ *aishdr++ = AIS_CMD_JMPCLOSE; *aishdr++ = params->ep; size = (aishdr - (uint32_t *)tparams->hdr) * sizeof(uint32_t); tparams->header_size = size; return 0; } static int aisimage_check_image_types(uint8_t type) { if (type == IH_TYPE_AISIMAGE) return EXIT_SUCCESS; else return EXIT_FAILURE; } static int aisimage_verify_header(unsigned char *ptr, int image_size, struct mkimage_params *params) { struct ais_header *ais_hdr = (struct ais_header *)ptr; if (ais_hdr->magic != AIS_MAGIC_WORD) return -FDT_ERR_BADSTRUCTURE; /* Store the total size to remember in print_hdr */ ais_img_size = image_size; return 0; } static void aisimage_set_header(void *ptr, struct stat *sbuf, int ifd, struct mkimage_params *params) { } int aisimage_check_params(struct mkimage_params *params) { if (!params) return CFG_INVALID; if (!strlen(params->imagename)) { fprintf(stderr, "Error: %s - Configuration file not specified, " "it is needed for aisimage generation\n", params->cmdname); return CFG_INVALID; } /* * Check parameters: * XIP is not allowed and verify that incompatible * parameters are not sent at the same time * For example, if list is required a data image must not be provided */ return (params->dflag && (params->fflag || params->lflag)) || (params->fflag && (params->dflag || params->lflag)) || (params->lflag && (params->dflag || params->fflag)) || (params->xflag) || !(strlen(params->imagename)); } /* * aisimage parameters */ static struct image_type_params aisimage_params = { .name = "TI Davinci AIS Boot Image support", .header_size = 0, .hdr = NULL, .check_image_type = aisimage_check_image_types, .verify_header = aisimage_verify_header, .print_header = aisimage_print_header, .set_header = aisimage_set_header, .check_params = aisimage_check_params, .vrec_header = aisimage_generate, }; void init_ais_image_type(void) { mkimage_register(&aisimage_params); }
1001-study-uboot
tools/aisimage.c
C
gpl3
11,455
#!/usr/bin/perl -w # (c) 2001, Dave Jones. (the file handling bit) # (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit) # (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite) # (c) 2008-2010 Andy Whitcroft <apw@canonical.com> # Licensed under the terms of the GNU GPL License version 2 use strict; my $P = $0; $P =~ s@.*/@@g; my $V = '0.32'; use Getopt::Long qw(:config no_auto_abbrev); my $quiet = 0; my $tree = 1; my $chk_signoff = 1; my $chk_patch = 1; my $tst_only; my $emacs = 0; my $terse = 0; my $file = 0; my $check = 0; my $summary = 1; my $mailback = 0; my $summary_file = 0; my $show_types = 0; my $root; my %debug; my %ignore_type = (); my @ignore = (); my $help = 0; my $configuration_file = ".checkpatch.conf"; sub help { my ($exitcode) = @_; print << "EOM"; Usage: $P [OPTION]... [FILE]... Version: $V Options: -q, --quiet quiet --no-tree run without a kernel tree --no-signoff do not check for 'Signed-off-by' line --patch treat FILE as patchfile (default) --emacs emacs compile window format --terse one line per report -f, --file treat FILE as regular source file --subjective, --strict enable more subjective tests --ignore TYPE(,TYPE2...) ignore various comma separated message types --show-types show the message "types" in the output --root=PATH PATH to the kernel tree root --no-summary suppress the per-file summary --mailback only produce a report in case of warnings/errors --summary-file include the filename in summary --debug KEY=[0|1] turn on/off debugging of KEY, where KEY is one of 'values', 'possible', 'type', and 'attr' (default is all off) --test-only=WORD report only warnings/errors containing WORD literally -h, --help, --version display this help and exit When FILE is - read standard input. EOM exit($exitcode); } my $conf = which_conf($configuration_file); if (-f $conf) { my @conf_args; open(my $conffile, '<', "$conf") or warn "$P: Can't find a readable $configuration_file file $!\n"; while (<$conffile>) { my $line = $_; $line =~ s/\s*\n?$//g; $line =~ s/^\s*//g; $line =~ s/\s+/ /g; next if ($line =~ m/^\s*#/); next if ($line =~ m/^\s*$/); my @words = split(" ", $line); foreach my $word (@words) { last if ($word =~ m/^#/); push (@conf_args, $word); } } close($conffile); unshift(@ARGV, @conf_args) if @conf_args; } GetOptions( 'q|quiet+' => \$quiet, 'tree!' => \$tree, 'signoff!' => \$chk_signoff, 'patch!' => \$chk_patch, 'emacs!' => \$emacs, 'terse!' => \$terse, 'f|file!' => \$file, 'subjective!' => \$check, 'strict!' => \$check, 'ignore=s' => \@ignore, 'show-types!' => \$show_types, 'root=s' => \$root, 'summary!' => \$summary, 'mailback!' => \$mailback, 'summary-file!' => \$summary_file, 'debug=s' => \%debug, 'test-only=s' => \$tst_only, 'h|help' => \$help, 'version' => \$help ) or help(1); help(0) if ($help); my $exit = 0; if ($#ARGV < 0) { print "$P: no input files\n"; exit(1); } @ignore = split(/,/, join(',',@ignore)); foreach my $word (@ignore) { $word =~ s/\s*\n?$//g; $word =~ s/^\s*//g; $word =~ s/\s+/ /g; $word =~ tr/[a-z]/[A-Z]/; next if ($word =~ m/^\s*#/); next if ($word =~ m/^\s*$/); $ignore_type{$word}++; } my $dbg_values = 0; my $dbg_possible = 0; my $dbg_type = 0; my $dbg_attr = 0; for my $key (keys %debug) { ## no critic eval "\${dbg_$key} = '$debug{$key}';"; die "$@" if ($@); } my $rpt_cleaners = 0; if ($terse) { $emacs = 1; $quiet++; } if ($tree) { if (defined $root) { if (!top_of_kernel_tree($root)) { die "$P: $root: --root does not point at a valid tree\n"; } } else { if (top_of_kernel_tree('.')) { $root = '.'; } elsif ($0 =~ m@(.*)/scripts/[^/]*$@ && top_of_kernel_tree($1)) { $root = $1; } } if (!defined $root) { print "Must be run from the top-level dir. of a kernel tree\n"; exit(2); } } my $emitted_corrupt = 0; our $Ident = qr{ [A-Za-z_][A-Za-z\d_]* (?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)* }x; our $Storage = qr{extern|static|asmlinkage}; our $Sparse = qr{ __user| __kernel| __force| __iomem| __must_check| __init_refok| __kprobes| __ref| __rcu }x; # Notes to $Attribute: # We need \b after 'init' otherwise 'initconst' will cause a false positive in a check our $Attribute = qr{ const| __percpu| __nocast| __safe| __bitwise__| __packed__| __packed2__| __naked| __maybe_unused| __always_unused| __noreturn| __used| __cold| __noclone| __deprecated| __read_mostly| __kprobes| __(?:mem|cpu|dev|)(?:initdata|initconst|init\b)| ____cacheline_aligned| ____cacheline_aligned_in_smp| ____cacheline_internodealigned_in_smp| __weak }x; our $Modifier; our $Inline = qr{inline|__always_inline|noinline}; our $Member = qr{->$Ident|\.$Ident|\[[^]]*\]}; our $Lval = qr{$Ident(?:$Member)*}; our $Constant = qr{(?:[0-9]+|0x[0-9a-fA-F]+)[UL]*}; our $Assignment = qr{(?:\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=)}; our $Compare = qr{<=|>=|==|!=|<|>}; our $Operators = qr{ <=|>=|==|!=| =>|->|<<|>>|<|>|!|~| &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|% }x; our $NonptrType; our $Type; our $Declare; our $UTF8 = qr { [\x09\x0A\x0D\x20-\x7E] # ASCII | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16 }x; our $typeTypedefs = qr{(?x: (?:__)?(?:u|s|be|le)(?:8|16|32|64)| atomic_t )}; our $logFunctions = qr{(?x: printk(?:_ratelimited|_once|)| [a-z0-9]+_(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)| WARN(?:_RATELIMIT|_ONCE|)| panic| MODULE_[A-Z_]+ )}; our $signature_tags = qr{(?xi: Signed-off-by:| Acked-by:| Tested-by:| Reviewed-by:| Reported-by:| To:| Cc: )}; our @typeList = ( qr{void}, qr{(?:unsigned\s+)?char}, qr{(?:unsigned\s+)?short}, qr{(?:unsigned\s+)?int}, qr{(?:unsigned\s+)?long}, qr{(?:unsigned\s+)?long\s+int}, qr{(?:unsigned\s+)?long\s+long}, qr{(?:unsigned\s+)?long\s+long\s+int}, qr{unsigned}, qr{float}, qr{double}, qr{bool}, qr{struct\s+$Ident}, qr{union\s+$Ident}, qr{enum\s+$Ident}, qr{${Ident}_t}, qr{${Ident}_handler}, qr{${Ident}_handler_fn}, ); our @modifierList = ( qr{fastcall}, ); our $allowed_asm_includes = qr{(?x: irq| memory )}; # memory.h: ARM has a custom one sub build_types { my $mods = "(?x: \n" . join("|\n ", @modifierList) . "\n)"; my $all = "(?x: \n" . join("|\n ", @typeList) . "\n)"; $Modifier = qr{(?:$Attribute|$Sparse|$mods)}; $NonptrType = qr{ (?:$Modifier\s+|const\s+)* (?: (?:typeof|__typeof__)\s*\(\s*\**\s*$Ident\s*\)| (?:$typeTypedefs\b)| (?:${all}\b) ) (?:\s+$Modifier|\s+const)* }x; $Type = qr{ $NonptrType (?:[\s\*]+\s*const|[\s\*]+|(?:\s*\[\s*\])+)? (?:\s+$Inline|\s+$Modifier)* }x; $Declare = qr{(?:$Storage\s+)?$Type}; } build_types(); our $match_balanced_parentheses = qr/(\((?:[^\(\)]+|(-1))*\))/; our $Typecast = qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*}; our $LvalOrFunc = qr{($Lval)\s*($match_balanced_parentheses{0,1})\s*}; sub deparenthesize { my ($string) = @_; return "" if (!defined($string)); $string =~ s@^\s*\(\s*@@g; $string =~ s@\s*\)\s*$@@g; $string =~ s@\s+@ @g; return $string; } $chk_signoff = 0 if ($file); my @dep_includes = (); my @dep_functions = (); my $removal = "Documentation/feature-removal-schedule.txt"; if ($tree && -f "$root/$removal") { open(my $REMOVE, '<', "$root/$removal") || die "$P: $removal: open failed - $!\n"; while (<$REMOVE>) { if (/^Check:\s+(.*\S)/) { for my $entry (split(/[, ]+/, $1)) { if ($entry =~ m@include/(.*)@) { push(@dep_includes, $1); } elsif ($entry !~ m@/@) { push(@dep_functions, $entry); } } } } close($REMOVE); } my @rawlines = (); my @lines = (); my $vname; for my $filename (@ARGV) { my $FILE; if ($file) { open($FILE, '-|', "diff -u /dev/null $filename") || die "$P: $filename: diff failed - $!\n"; } elsif ($filename eq '-') { open($FILE, '<&STDIN'); } else { open($FILE, '<', "$filename") || die "$P: $filename: open failed - $!\n"; } if ($filename eq '-') { $vname = 'Your patch'; } else { $vname = $filename; } while (<$FILE>) { chomp; push(@rawlines, $_); } close($FILE); if (!process($filename)) { $exit = 1; } @rawlines = (); @lines = (); } exit($exit); sub top_of_kernel_tree { my ($root) = @_; my @tree_check = ( "COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile", "README", "Documentation", "arch", "include", "drivers", "fs", "init", "ipc", "kernel", "lib", "scripts", ); foreach my $check (@tree_check) { if (! -e $root . '/' . $check) { return 0; } } return 1; } sub parse_email { my ($formatted_email) = @_; my $name = ""; my $address = ""; my $comment = ""; if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) { $name = $1; $address = $2; $comment = $3 if defined $3; } elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) { $address = $1; $comment = $2 if defined $2; } elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) { $address = $1; $comment = $2 if defined $2; $formatted_email =~ s/$address.*$//; $name = $formatted_email; $name =~ s/^\s+|\s+$//g; $name =~ s/^\"|\"$//g; # If there's a name left after stripping spaces and # leading quotes, and the address doesn't have both # leading and trailing angle brackets, the address # is invalid. ie: # "joe smith joe@smith.com" bad # "joe smith <joe@smith.com" bad if ($name ne "" && $address !~ /^<[^>]+>$/) { $name = ""; $address = ""; $comment = ""; } } $name =~ s/^\s+|\s+$//g; $name =~ s/^\"|\"$//g; $address =~ s/^\s+|\s+$//g; $address =~ s/^\<|\>$//g; if ($name =~ /[^\w \-]/i) { ##has "must quote" chars $name =~ s/(?<!\\)"/\\"/g; ##escape quotes $name = "\"$name\""; } return ($name, $address, $comment); } sub format_email { my ($name, $address) = @_; my $formatted_email; $name =~ s/^\s+|\s+$//g; $name =~ s/^\"|\"$//g; $address =~ s/^\s+|\s+$//g; if ($name =~ /[^\w \-]/i) { ##has "must quote" chars $name =~ s/(?<!\\)"/\\"/g; ##escape quotes $name = "\"$name\""; } if ("$name" eq "") { $formatted_email = "$address"; } else { $formatted_email = "$name <$address>"; } return $formatted_email; } sub which_conf { my ($conf) = @_; foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) { if (-e "$path/$conf") { return "$path/$conf"; } } return ""; } sub expand_tabs { my ($str) = @_; my $res = ''; my $n = 0; for my $c (split(//, $str)) { if ($c eq "\t") { $res .= ' '; $n++; for (; ($n % 8) != 0; $n++) { $res .= ' '; } next; } $res .= $c; $n++; } return $res; } sub copy_spacing { (my $res = shift) =~ tr/\t/ /c; return $res; } sub line_stats { my ($line) = @_; # Drop the diff line leader and expand tabs $line =~ s/^.//; $line = expand_tabs($line); # Pick the indent from the front of the line. my ($white) = ($line =~ /^(\s*)/); return (length($line), length($white)); } my $sanitise_quote = ''; sub sanitise_line_reset { my ($in_comment) = @_; if ($in_comment) { $sanitise_quote = '*/'; } else { $sanitise_quote = ''; } } sub sanitise_line { my ($line) = @_; my $res = ''; my $l = ''; my $qlen = 0; my $off = 0; my $c; # Always copy over the diff marker. $res = substr($line, 0, 1); for ($off = 1; $off < length($line); $off++) { $c = substr($line, $off, 1); # Comments we are wacking completly including the begin # and end, all to $;. if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') { $sanitise_quote = '*/'; substr($res, $off, 2, "$;$;"); $off++; next; } if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') { $sanitise_quote = ''; substr($res, $off, 2, "$;$;"); $off++; next; } if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') { $sanitise_quote = '//'; substr($res, $off, 2, $sanitise_quote); $off++; next; } # A \ in a string means ignore the next character. if (($sanitise_quote eq "'" || $sanitise_quote eq '"') && $c eq "\\") { substr($res, $off, 2, 'XX'); $off++; next; } # Regular quotes. if ($c eq "'" || $c eq '"') { if ($sanitise_quote eq '') { $sanitise_quote = $c; substr($res, $off, 1, $c); next; } elsif ($sanitise_quote eq $c) { $sanitise_quote = ''; } } #print "c<$c> SQ<$sanitise_quote>\n"; if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") { substr($res, $off, 1, $;); } elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") { substr($res, $off, 1, $;); } elsif ($off != 0 && $sanitise_quote && $c ne "\t") { substr($res, $off, 1, 'X'); } else { substr($res, $off, 1, $c); } } if ($sanitise_quote eq '//') { $sanitise_quote = ''; } # The pathname on a #include may be surrounded by '<' and '>'. if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) { my $clean = 'X' x length($1); $res =~ s@\<.*\>@<$clean>@; # The whole of a #error is a string. } elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) { my $clean = 'X' x length($1); $res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@; } return $res; } sub ctx_statement_block { my ($linenr, $remain, $off) = @_; my $line = $linenr - 1; my $blk = ''; my $soff = $off; my $coff = $off - 1; my $coff_set = 0; my $loff = 0; my $type = ''; my $level = 0; my @stack = (); my $p; my $c; my $len = 0; my $remainder; while (1) { @stack = (['', 0]) if ($#stack == -1); #warn "CSB: blk<$blk> remain<$remain>\n"; # If we are about to drop off the end, pull in more # context. if ($off >= $len) { for (; $remain > 0; $line++) { last if (!defined $lines[$line]); next if ($lines[$line] =~ /^-/); $remain--; $loff = $len; $blk .= $lines[$line] . "\n"; $len = length($blk); $line++; last; } # Bail if there is no further context. #warn "CSB: blk<$blk> off<$off> len<$len>\n"; if ($off >= $len) { last; } } $p = $c; $c = substr($blk, $off, 1); $remainder = substr($blk, $off); #warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n"; # Handle nested #if/#else. if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) { push(@stack, [ $type, $level ]); } elsif ($remainder =~ /^#\s*(?:else|elif)\b/) { ($type, $level) = @{$stack[$#stack - 1]}; } elsif ($remainder =~ /^#\s*endif\b/) { ($type, $level) = @{pop(@stack)}; } # Statement ends at the ';' or a close '}' at the # outermost level. if ($level == 0 && $c eq ';') { last; } # An else is really a conditional as long as its not else if if ($level == 0 && $coff_set == 0 && (!defined($p) || $p =~ /(?:\s|\}|\+)/) && $remainder =~ /^(else)(?:\s|{)/ && $remainder !~ /^else\s+if\b/) { $coff = $off + length($1) - 1; $coff_set = 1; #warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n"; #warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n"; } if (($type eq '' || $type eq '(') && $c eq '(') { $level++; $type = '('; } if ($type eq '(' && $c eq ')') { $level--; $type = ($level != 0)? '(' : ''; if ($level == 0 && $coff < $soff) { $coff = $off; $coff_set = 1; #warn "CSB: mark coff<$coff>\n"; } } if (($type eq '' || $type eq '{') && $c eq '{') { $level++; $type = '{'; } if ($type eq '{' && $c eq '}') { $level--; $type = ($level != 0)? '{' : ''; if ($level == 0) { if (substr($blk, $off + 1, 1) eq ';') { $off++; } last; } } $off++; } # We are truly at the end, so shuffle to the next line. if ($off == $len) { $loff = $len + 1; $line++; $remain--; } my $statement = substr($blk, $soff, $off - $soff + 1); my $condition = substr($blk, $soff, $coff - $soff + 1); #warn "STATEMENT<$statement>\n"; #warn "CONDITION<$condition>\n"; #print "coff<$coff> soff<$off> loff<$loff>\n"; return ($statement, $condition, $line, $remain + 1, $off - $loff + 1, $level); } sub statement_lines { my ($stmt) = @_; # Strip the diff line prefixes and rip blank lines at start and end. $stmt =~ s/(^|\n)./$1/g; $stmt =~ s/^\s*//; $stmt =~ s/\s*$//; my @stmt_lines = ($stmt =~ /\n/g); return $#stmt_lines + 2; } sub statement_rawlines { my ($stmt) = @_; my @stmt_lines = ($stmt =~ /\n/g); return $#stmt_lines + 2; } sub statement_block_size { my ($stmt) = @_; $stmt =~ s/(^|\n)./$1/g; $stmt =~ s/^\s*{//; $stmt =~ s/}\s*$//; $stmt =~ s/^\s*//; $stmt =~ s/\s*$//; my @stmt_lines = ($stmt =~ /\n/g); my @stmt_statements = ($stmt =~ /;/g); my $stmt_lines = $#stmt_lines + 2; my $stmt_statements = $#stmt_statements + 1; if ($stmt_lines > $stmt_statements) { return $stmt_lines; } else { return $stmt_statements; } } sub ctx_statement_full { my ($linenr, $remain, $off) = @_; my ($statement, $condition, $level); my (@chunks); # Grab the first conditional/block pair. ($statement, $condition, $linenr, $remain, $off, $level) = ctx_statement_block($linenr, $remain, $off); #print "F: c<$condition> s<$statement> remain<$remain>\n"; push(@chunks, [ $condition, $statement ]); if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) { return ($level, $linenr, @chunks); } # Pull in the following conditional/block pairs and see if they # could continue the statement. for (;;) { ($statement, $condition, $linenr, $remain, $off, $level) = ctx_statement_block($linenr, $remain, $off); #print "C: c<$condition> s<$statement> remain<$remain>\n"; last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s)); #print "C: push\n"; push(@chunks, [ $condition, $statement ]); } return ($level, $linenr, @chunks); } sub ctx_block_get { my ($linenr, $remain, $outer, $open, $close, $off) = @_; my $line; my $start = $linenr - 1; my $blk = ''; my @o; my @c; my @res = (); my $level = 0; my @stack = ($level); for ($line = $start; $remain > 0; $line++) { next if ($rawlines[$line] =~ /^-/); $remain--; $blk .= $rawlines[$line]; # Handle nested #if/#else. if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) { push(@stack, $level); } elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) { $level = $stack[$#stack - 1]; } elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) { $level = pop(@stack); } foreach my $c (split(//, $lines[$line])) { ##print "C<$c>L<$level><$open$close>O<$off>\n"; if ($off > 0) { $off--; next; } if ($c eq $close && $level > 0) { $level--; last if ($level == 0); } elsif ($c eq $open) { $level++; } } if (!$outer || $level <= 1) { push(@res, $rawlines[$line]); } last if ($level == 0); } return ($level, @res); } sub ctx_block_outer { my ($linenr, $remain) = @_; my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0); return @r; } sub ctx_block { my ($linenr, $remain) = @_; my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0); return @r; } sub ctx_statement { my ($linenr, $remain, $off) = @_; my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off); return @r; } sub ctx_block_level { my ($linenr, $remain) = @_; return ctx_block_get($linenr, $remain, 0, '{', '}', 0); } sub ctx_statement_level { my ($linenr, $remain, $off) = @_; return ctx_block_get($linenr, $remain, 0, '(', ')', $off); } sub ctx_locate_comment { my ($first_line, $end_line) = @_; # Catch a comment on the end of the line itself. my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@); return $current_comment if (defined $current_comment); # Look through the context and try and figure out if there is a # comment. my $in_comment = 0; $current_comment = ''; for (my $linenr = $first_line; $linenr < $end_line; $linenr++) { my $line = $rawlines[$linenr - 1]; #warn " $line\n"; if ($linenr == $first_line and $line =~ m@^.\s*\*@) { $in_comment = 1; } if ($line =~ m@/\*@) { $in_comment = 1; } if (!$in_comment && $current_comment ne '') { $current_comment = ''; } $current_comment .= $line . "\n" if ($in_comment); if ($line =~ m@\*/@) { $in_comment = 0; } } chomp($current_comment); return($current_comment); } sub ctx_has_comment { my ($first_line, $end_line) = @_; my $cmt = ctx_locate_comment($first_line, $end_line); ##print "LINE: $rawlines[$end_line - 1 ]\n"; ##print "CMMT: $cmt\n"; return ($cmt ne ''); } sub raw_line { my ($linenr, $cnt) = @_; my $offset = $linenr - 1; $cnt++; my $line; while ($cnt) { $line = $rawlines[$offset++]; next if (defined($line) && $line =~ /^-/); $cnt--; } return $line; } sub cat_vet { my ($vet) = @_; my ($res, $coded); $res = ''; while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) { $res .= $1; if ($2 ne '') { $coded = sprintf("^%c", unpack('C', $2) + 64); $res .= $coded; } } $res =~ s/$/\$/; return $res; } my $av_preprocessor = 0; my $av_pending; my @av_paren_type; my $av_pend_colon; sub annotate_reset { $av_preprocessor = 0; $av_pending = '_'; @av_paren_type = ('E'); $av_pend_colon = 'O'; } sub annotate_values { my ($stream, $type) = @_; my $res; my $var = '_' x length($stream); my $cur = $stream; print "$stream\n" if ($dbg_values > 1); while (length($cur)) { @av_paren_type = ('E') if ($#av_paren_type < 0); print " <" . join('', @av_paren_type) . "> <$type> <$av_pending>" if ($dbg_values > 1); if ($cur =~ /^(\s+)/o) { print "WS($1)\n" if ($dbg_values > 1); if ($1 =~ /\n/ && $av_preprocessor) { $type = pop(@av_paren_type); $av_preprocessor = 0; } } elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') { print "CAST($1)\n" if ($dbg_values > 1); push(@av_paren_type, $type); $type = 'C'; } elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) { print "DECLARE($1)\n" if ($dbg_values > 1); $type = 'T'; } elsif ($cur =~ /^($Modifier)\s*/) { print "MODIFIER($1)\n" if ($dbg_values > 1); $type = 'T'; } elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) { print "DEFINE($1,$2)\n" if ($dbg_values > 1); $av_preprocessor = 1; push(@av_paren_type, $type); if ($2 ne '') { $av_pending = 'N'; } $type = 'E'; } elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) { print "UNDEF($1)\n" if ($dbg_values > 1); $av_preprocessor = 1; push(@av_paren_type, $type); } elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) { print "PRE_START($1)\n" if ($dbg_values > 1); $av_preprocessor = 1; push(@av_paren_type, $type); push(@av_paren_type, $type); $type = 'E'; } elsif ($cur =~ /^(\#\s*(?:else|elif))/o) { print "PRE_RESTART($1)\n" if ($dbg_values > 1); $av_preprocessor = 1; push(@av_paren_type, $av_paren_type[$#av_paren_type]); $type = 'E'; } elsif ($cur =~ /^(\#\s*(?:endif))/o) { print "PRE_END($1)\n" if ($dbg_values > 1); $av_preprocessor = 1; # Assume all arms of the conditional end as this # one does, and continue as if the #endif was not here. pop(@av_paren_type); push(@av_paren_type, $type); $type = 'E'; } elsif ($cur =~ /^(\\\n)/o) { print "PRECONT($1)\n" if ($dbg_values > 1); } elsif ($cur =~ /^(__attribute__)\s*\(?/o) { print "ATTR($1)\n" if ($dbg_values > 1); $av_pending = $type; $type = 'N'; } elsif ($cur =~ /^(sizeof)\s*(\()?/o) { print "SIZEOF($1)\n" if ($dbg_values > 1); if (defined $2) { $av_pending = 'V'; } $type = 'N'; } elsif ($cur =~ /^(if|while|for)\b/o) { print "COND($1)\n" if ($dbg_values > 1); $av_pending = 'E'; $type = 'N'; } elsif ($cur =~/^(case)/o) { print "CASE($1)\n" if ($dbg_values > 1); $av_pend_colon = 'C'; $type = 'N'; } elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) { print "KEYWORD($1)\n" if ($dbg_values > 1); $type = 'N'; } elsif ($cur =~ /^(\()/o) { print "PAREN('$1')\n" if ($dbg_values > 1); push(@av_paren_type, $av_pending); $av_pending = '_'; $type = 'N'; } elsif ($cur =~ /^(\))/o) { my $new_type = pop(@av_paren_type); if ($new_type ne '_') { $type = $new_type; print "PAREN('$1') -> $type\n" if ($dbg_values > 1); } else { print "PAREN('$1')\n" if ($dbg_values > 1); } } elsif ($cur =~ /^($Ident)\s*\(/o) { print "FUNC($1)\n" if ($dbg_values > 1); $type = 'V'; $av_pending = 'V'; } elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) { if (defined $2 && $type eq 'C' || $type eq 'T') { $av_pend_colon = 'B'; } elsif ($type eq 'E') { $av_pend_colon = 'L'; } print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1); $type = 'V'; } elsif ($cur =~ /^($Ident|$Constant)/o) { print "IDENT($1)\n" if ($dbg_values > 1); $type = 'V'; } elsif ($cur =~ /^($Assignment)/o) { print "ASSIGN($1)\n" if ($dbg_values > 1); $type = 'N'; } elsif ($cur =~/^(;|{|})/) { print "END($1)\n" if ($dbg_values > 1); $type = 'E'; $av_pend_colon = 'O'; } elsif ($cur =~/^(,)/) { print "COMMA($1)\n" if ($dbg_values > 1); $type = 'C'; } elsif ($cur =~ /^(\?)/o) { print "QUESTION($1)\n" if ($dbg_values > 1); $type = 'N'; } elsif ($cur =~ /^(:)/o) { print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1); substr($var, length($res), 1, $av_pend_colon); if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') { $type = 'E'; } else { $type = 'N'; } $av_pend_colon = 'O'; } elsif ($cur =~ /^(\[)/o) { print "CLOSE($1)\n" if ($dbg_values > 1); $type = 'N'; } elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) { my $variant; print "OPV($1)\n" if ($dbg_values > 1); if ($type eq 'V') { $variant = 'B'; } else { $variant = 'U'; } substr($var, length($res), 1, $variant); $type = 'N'; } elsif ($cur =~ /^($Operators)/o) { print "OP($1)\n" if ($dbg_values > 1); if ($1 ne '++' && $1 ne '--') { $type = 'N'; } } elsif ($cur =~ /(^.)/o) { print "C($1)\n" if ($dbg_values > 1); } if (defined $1) { $cur = substr($cur, length($1)); $res .= $type x length($1); } } return ($res, $var); } sub possible { my ($possible, $line) = @_; my $notPermitted = qr{(?: ^(?: $Modifier| $Storage| $Type| DEFINE_\S+ )$| ^(?: goto| return| case| else| asm|__asm__| do )(?:\s|$)| ^(?:typedef|struct|enum)\b )}x; warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2); if ($possible !~ $notPermitted) { # Check for modifiers. $possible =~ s/\s*$Storage\s*//g; $possible =~ s/\s*$Sparse\s*//g; if ($possible =~ /^\s*$/) { } elsif ($possible =~ /\s/) { $possible =~ s/\s*$Type\s*//g; for my $modifier (split(' ', $possible)) { if ($modifier !~ $notPermitted) { warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible); push(@modifierList, $modifier); } } } else { warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible); push(@typeList, $possible); } build_types(); } else { warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1); } } my $prefix = ''; sub show_type { return !defined $ignore_type{$_[0]}; } sub report { if (!show_type($_[1]) || (defined $tst_only && $_[2] !~ /\Q$tst_only\E/)) { return 0; } my $line; if ($show_types) { $line = "$prefix$_[0]:$_[1]: $_[2]\n"; } else { $line = "$prefix$_[0]: $_[2]\n"; } $line = (split('\n', $line))[0] . "\n" if ($terse); push(our @report, $line); return 1; } sub report_dump { our @report; } sub ERROR { if (report("ERROR", $_[0], $_[1])) { our $clean = 0; our $cnt_error++; } } sub WARN { if (report("WARNING", $_[0], $_[1])) { our $clean = 0; our $cnt_warn++; } } sub CHK { if ($check && report("CHECK", $_[0], $_[1])) { our $clean = 0; our $cnt_chk++; } } sub check_absolute_file { my ($absolute, $herecurr) = @_; my $file = $absolute; ##print "absolute<$absolute>\n"; # See if any suffix of this path is a path within the tree. while ($file =~ s@^[^/]*/@@) { if (-f "$root/$file") { ##print "file<$file>\n"; last; } } if (! -f _) { return 0; } # It is, so see if the prefix is acceptable. my $prefix = $absolute; substr($prefix, -length($file)) = ''; ##print "prefix<$prefix>\n"; if ($prefix ne ".../") { WARN("USE_RELATIVE_PATH", "use relative pathname instead of absolute in changelog text\n" . $herecurr); } } sub process { my $filename = shift; my $linenr=0; my $prevline=""; my $prevrawline=""; my $stashline=""; my $stashrawline=""; my $length; my $indent; my $previndent=0; my $stashindent=0; our $clean = 1; my $signoff = 0; my $is_patch = 0; our @report = (); our $cnt_lines = 0; our $cnt_error = 0; our $cnt_warn = 0; our $cnt_chk = 0; # Trace the real file/line as we go. my $realfile = ''; my $realline = 0; my $realcnt = 0; my $here = ''; my $in_comment = 0; my $comment_edge = 0; my $first_line = 0; my $p1_prefix = ''; my $prev_values = 'E'; # suppression flags my %suppress_ifbraces; my %suppress_whiletrailers; my %suppress_export; # Pre-scan the patch sanitizing the lines. # Pre-scan the patch looking for any __setup documentation. # my @setup_docs = (); my $setup_docs = 0; sanitise_line_reset(); my $line; foreach my $rawline (@rawlines) { $linenr++; $line = $rawline; if ($rawline=~/^\+\+\+\s+(\S+)/) { $setup_docs = 0; if ($1 =~ m@Documentation/kernel-parameters.txt$@) { $setup_docs = 1; } #next; } if ($rawline=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) { $realline=$1-1; if (defined $2) { $realcnt=$3+1; } else { $realcnt=1+1; } $in_comment = 0; # Guestimate if this is a continuing comment. Run # the context looking for a comment "edge". If this # edge is a close comment then we must be in a comment # at context start. my $edge; my $cnt = $realcnt; for (my $ln = $linenr + 1; $cnt > 0; $ln++) { next if (defined $rawlines[$ln - 1] && $rawlines[$ln - 1] =~ /^-/); $cnt--; #print "RAW<$rawlines[$ln - 1]>\n"; last if (!defined $rawlines[$ln - 1]); if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ && $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) { ($edge) = $1; last; } } if (defined $edge && $edge eq '*/') { $in_comment = 1; } # Guestimate if this is a continuing comment. If this # is the start of a diff block and this line starts # ' *' then it is very likely a comment. if (!defined $edge && $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@) { $in_comment = 1; } ##print "COMMENT:$in_comment edge<$edge> $rawline\n"; sanitise_line_reset($in_comment); } elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) { # Standardise the strings and chars within the input to # simplify matching -- only bother with positive lines. $line = sanitise_line($rawline); } push(@lines, $line); if ($realcnt > 1) { $realcnt-- if ($line =~ /^(?:\+| |$)/); } else { $realcnt = 0; } #print "==>$rawline\n"; #print "-->$line\n"; if ($setup_docs && $line =~ /^\+/) { push(@setup_docs, $line); } } $prefix = ''; $realcnt = 0; $linenr = 0; foreach my $line (@lines) { $linenr++; my $rawline = $rawlines[$linenr - 1]; #extract the line range in the file after the patch is applied if ($line=~/^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) { $is_patch = 1; $first_line = $linenr + 1; $realline=$1-1; if (defined $2) { $realcnt=$3+1; } else { $realcnt=1+1; } annotate_reset(); $prev_values = 'E'; %suppress_ifbraces = (); %suppress_whiletrailers = (); %suppress_export = (); next; # track the line number as we move through the hunk, note that # new versions of GNU diff omit the leading space on completely # blank context lines so we need to count that too. } elsif ($line =~ /^( |\+|$)/) { $realline++; $realcnt-- if ($realcnt != 0); # Measure the line length and indent. ($length, $indent) = line_stats($rawline); # Track the previous line. ($prevline, $stashline) = ($stashline, $line); ($previndent, $stashindent) = ($stashindent, $indent); ($prevrawline, $stashrawline) = ($stashrawline, $rawline); #warn "line<$line>\n"; } elsif ($realcnt == 1) { $realcnt--; } my $hunk_line = ($realcnt != 0); #make up the handle for any error we report on this line $prefix = "$filename:$realline: " if ($emacs && $file); $prefix = "$filename:$linenr: " if ($emacs && !$file); $here = "#$linenr: " if (!$file); $here = "#$realline: " if ($file); # extract the filename as it passes if ($line =~ /^diff --git.*?(\S+)$/) { $realfile = $1; $realfile =~ s@^([^/]*)/@@; } elsif ($line =~ /^\+\+\+\s+(\S+)/) { $realfile = $1; $realfile =~ s@^([^/]*)/@@; $p1_prefix = $1; if (!$file && $tree && $p1_prefix ne '' && -e "$root/$p1_prefix") { WARN("PATCH_PREFIX", "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n"); } if ($realfile =~ m@^include/asm/@) { ERROR("MODIFIED_INCLUDE_ASM", "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n"); } next; } $here .= "FILE: $realfile:$realline:" if ($realcnt != 0); my $hereline = "$here\n$rawline\n"; my $herecurr = "$here\n$rawline\n"; my $hereprev = "$here\n$prevrawline\n$rawline\n"; $cnt_lines++ if ($realcnt != 0); # Check for incorrect file permissions if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) { my $permhere = $here . "FILE: $realfile\n"; if ($realfile =~ /(Makefile|Kconfig|\.c|\.h|\.S|\.tmpl)$/) { ERROR("EXECUTE_PERMISSIONS", "do not set execute permissions for source files\n" . $permhere); } } # Check the patch for a signoff: if ($line =~ /^\s*signed-off-by:/i) { $signoff++; } # Check signature styles if ($line =~ /^(\s*)($signature_tags)(\s*)(.*)/) { my $space_before = $1; my $sign_off = $2; my $space_after = $3; my $email = $4; my $ucfirst_sign_off = ucfirst(lc($sign_off)); if (defined $space_before && $space_before ne "") { WARN("BAD_SIGN_OFF", "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr); } if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) { WARN("BAD_SIGN_OFF", "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr); } if (!defined $space_after || $space_after ne " ") { WARN("BAD_SIGN_OFF", "Use a single space after $ucfirst_sign_off\n" . $herecurr); } my ($email_name, $email_address, $comment) = parse_email($email); my $suggested_email = format_email(($email_name, $email_address)); if ($suggested_email eq "") { ERROR("BAD_SIGN_OFF", "Unrecognized email address: '$email'\n" . $herecurr); } else { my $dequoted = $suggested_email; $dequoted =~ s/^"//; $dequoted =~ s/" </ </; # Don't force email to have quotes # Allow just an angle bracketed address if ("$dequoted$comment" ne $email && "<$email_address>$comment" ne $email && "$suggested_email$comment" ne $email) { WARN("BAD_SIGN_OFF", "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr); } } } # Check for wrappage within a valid hunk of the file if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) { ERROR("CORRUPTED_PATCH", "patch seems to be corrupt (line wrapped?)\n" . $herecurr) if (!$emitted_corrupt++); } # Check for absolute kernel paths. if ($tree) { while ($line =~ m{(?:^|\s)(/\S*)}g) { my $file = $1; if ($file =~ m{^(.*?)(?::\d+)+:?$} && check_absolute_file($1, $herecurr)) { # } else { check_absolute_file($file, $herecurr); } } } # UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php if (($realfile =~ /^$/ || $line =~ /^\+/) && $rawline !~ m/^$UTF8*$/) { my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/); my $blank = copy_spacing($rawline); my $ptr = substr($blank, 0, length($utf8_prefix)) . "^"; my $hereptr = "$hereline$ptr\n"; CHK("INVALID_UTF8", "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr); } # ignore non-hunk lines and lines being removed next if (!$hunk_line || $line =~ /^-/); #trailing whitespace if ($line =~ /^\+.*\015/) { my $herevet = "$here\n" . cat_vet($rawline) . "\n"; ERROR("DOS_LINE_ENDINGS", "DOS line endings\n" . $herevet); } elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) { my $herevet = "$here\n" . cat_vet($rawline) . "\n"; ERROR("TRAILING_WHITESPACE", "trailing whitespace\n" . $herevet); $rpt_cleaners = 1; } # check for Kconfig help text having a real description # Only applies when adding the entry originally, after that we do not have # sufficient context to determine whether it is indeed long enough. if ($realfile =~ /Kconfig/ && $line =~ /\+\s*(?:---)?help(?:---)?$/) { my $length = 0; my $cnt = $realcnt; my $ln = $linenr + 1; my $f; my $is_end = 0; while ($cnt > 0 && defined $lines[$ln - 1]) { $f = $lines[$ln - 1]; $cnt-- if ($lines[$ln - 1] !~ /^-/); $is_end = $lines[$ln - 1] =~ /^\+/; $ln++; next if ($f =~ /^-/); $f =~ s/^.//; $f =~ s/#.*//; $f =~ s/^\s+//; next if ($f =~ /^$/); if ($f =~ /^\s*config\s/) { $is_end = 1; last; } $length++; } WARN("CONFIG_DESCRIPTION", "please write a paragraph that describes the config symbol fully\n" . $herecurr) if ($is_end && $length < 4); #print "is_end<$is_end> length<$length>\n"; } # check we are in a valid source file if not then ignore this hunk next if ($realfile !~ /\.(h|c|s|S|pl|sh)$/); #80 column limit if ($line =~ /^\+/ && $prevrawline !~ /\/\*\*/ && $rawline !~ /^.\s*\*\s*\@$Ident\s/ && !($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(KERN_\S+\s*|[^"]*))?"[X\t]*"\s*(?:|,|\)\s*;)\s*$/ || $line =~ /^\+\s*"[^"]*"\s*(?:\s*|,|\)\s*;)\s*$/) && $length > 80) { WARN("LONG_LINE", "line over 80 characters\n" . $herecurr); } # check for spaces before a quoted newline if ($rawline =~ /^.*\".*\s\\n/) { WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE", "unnecessary whitespace before a quoted newline\n" . $herecurr); } # check for adding lines without a newline. if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) { WARN("MISSING_EOF_NEWLINE", "adding a line without newline at end of file\n" . $herecurr); } # Blackfin: use hi/lo macros if ($realfile =~ m@arch/blackfin/.*\.S$@) { if ($line =~ /\.[lL][[:space:]]*=.*&[[:space:]]*0x[fF][fF][fF][fF]/) { my $herevet = "$here\n" . cat_vet($line) . "\n"; ERROR("LO_MACRO", "use the LO() macro, not (... & 0xFFFF)\n" . $herevet); } if ($line =~ /\.[hH][[:space:]]*=.*>>[[:space:]]*16/) { my $herevet = "$here\n" . cat_vet($line) . "\n"; ERROR("HI_MACRO", "use the HI() macro, not (... >> 16)\n" . $herevet); } } # check we are in a valid source file C or perl if not then ignore this hunk next if ($realfile !~ /\.(h|c|pl)$/); # at the beginning of a line any tabs must come first and anything # more than 8 must use tabs. if ($rawline =~ /^\+\s* \t\s*\S/ || $rawline =~ /^\+\s* \s*/) { my $herevet = "$here\n" . cat_vet($rawline) . "\n"; ERROR("CODE_INDENT", "code indent should use tabs where possible\n" . $herevet); $rpt_cleaners = 1; } # check for space before tabs. if ($rawline =~ /^\+/ && $rawline =~ / \t/) { my $herevet = "$here\n" . cat_vet($rawline) . "\n"; WARN("SPACE_BEFORE_TAB", "please, no space before tabs\n" . $herevet); } # check for spaces at the beginning of a line. # Exceptions: # 1) within comments # 2) indented preprocessor commands # 3) hanging labels if ($rawline =~ /^\+ / && $line !~ /\+ *(?:$;|#|$Ident:)/) { my $herevet = "$here\n" . cat_vet($rawline) . "\n"; WARN("LEADING_SPACE", "please, no spaces at the start of a line\n" . $herevet); } # check we are in a valid C source file if not then ignore this hunk next if ($realfile !~ /\.(h|c)$/); # check for RCS/CVS revision markers if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) { WARN("CVS_KEYWORD", "CVS style keyword markers, these will _not_ be updated\n". $herecurr); } # Blackfin: don't use __builtin_bfin_[cs]sync if ($line =~ /__builtin_bfin_csync/) { my $herevet = "$here\n" . cat_vet($line) . "\n"; ERROR("CSYNC", "use the CSYNC() macro in asm/blackfin.h\n" . $herevet); } if ($line =~ /__builtin_bfin_ssync/) { my $herevet = "$here\n" . cat_vet($line) . "\n"; ERROR("SSYNC", "use the SSYNC() macro in asm/blackfin.h\n" . $herevet); } # Check for potential 'bare' types my ($stat, $cond, $line_nr_next, $remain_next, $off_next, $realline_next); if ($realcnt && $line =~ /.\s*\S/) { ($stat, $cond, $line_nr_next, $remain_next, $off_next) = ctx_statement_block($linenr, $realcnt, 0); $stat =~ s/\n./\n /g; $cond =~ s/\n./\n /g; # Find the real next line. $realline_next = $line_nr_next; if (defined $realline_next && (!defined $lines[$realline_next - 1] || substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) { $realline_next++; } my $s = $stat; $s =~ s/{.*$//s; # Ignore goto labels. if ($s =~ /$Ident:\*$/s) { # Ignore functions being called } elsif ($s =~ /^.\s*$Ident\s*\(/s) { } elsif ($s =~ /^.\s*else\b/s) { # declarations always start with types } elsif ($prev_values eq 'E' && $s =~ /^.\s*(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?((?:\s*$Ident)+?)\b(?:\s+$Sparse)?\s*\**\s*(?:$Ident|\(\*[^\)]*\))(?:\s*$Modifier)?\s*(?:;|=|,|\()/s) { my $type = $1; $type =~ s/\s+/ /g; possible($type, "A:" . $s); # definitions in global scope can only start with types } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) { possible($1, "B:" . $s); } # any (foo ... *) is a pointer cast, and foo is a type while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) { possible($1, "C:" . $s); } # Check for any sort of function declaration. # int foo(something bar, other baz); # void (*store_gdt)(x86_descr_ptr *); if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) { my ($name_len) = length($1); my $ctx = $s; substr($ctx, 0, $name_len + 1, ''); $ctx =~ s/\)[^\)]*$//; for my $arg (split(/\s*,\s*/, $ctx)) { if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) { possible($1, "D:" . $s); } } } } # # Checks which may be anchored in the context. # # Check for switch () and associated case and default # statements should be at the same indent. if ($line=~/\bswitch\s*\(.*\)/) { my $err = ''; my $sep = ''; my @ctx = ctx_block_outer($linenr, $realcnt); shift(@ctx); for my $ctx (@ctx) { my ($clen, $cindent) = line_stats($ctx); if ($ctx =~ /^\+\s*(case\s+|default:)/ && $indent != $cindent) { $err .= "$sep$ctx\n"; $sep = ''; } else { $sep = "[...]\n"; } } if ($err ne '') { ERROR("SWITCH_CASE_INDENT_LEVEL", "switch and case should be at the same indent\n$hereline$err"); } } # if/while/etc brace do not go on next line, unless defining a do while loop, # or if that brace on the next line is for something else if ($line =~ /(.*)\b((?:if|while|for|switch)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) { my $pre_ctx = "$1$2"; my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0); my $ctx_cnt = $realcnt - $#ctx - 1; my $ctx = join("\n", @ctx); my $ctx_ln = $linenr; my $ctx_skip = $realcnt; while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt && defined $lines[$ctx_ln - 1] && $lines[$ctx_ln - 1] =~ /^-/)) { ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n"; $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/); $ctx_ln++; } #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n"; #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n"; if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln -1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) { ERROR("OPEN_BRACE", "that open brace { should be on the previous line\n" . "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n"); } if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ && $ctx =~ /\)\s*\;\s*$/ && defined $lines[$ctx_ln - 1]) { my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]); if ($nindent > $indent) { WARN("TRAILING_SEMICOLON", "trailing semicolon indicates no statements, indent implies otherwise\n" . "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n"); } } } # Check relative indent for conditionals and blocks. if ($line =~ /\b(?:(?:if|while|for)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) { my ($s, $c) = ($stat, $cond); substr($s, 0, length($c), ''); # Make sure we remove the line prefixes as we have # none on the first line, and are going to readd them # where necessary. $s =~ s/\n./\n/gs; # Find out how long the conditional actually is. my @newlines = ($c =~ /\n/gs); my $cond_lines = 1 + $#newlines; # We want to check the first line inside the block # starting at the end of the conditional, so remove: # 1) any blank line termination # 2) any opening brace { on end of the line # 3) any do (...) { my $continuation = 0; my $check = 0; $s =~ s/^.*\bdo\b//; $s =~ s/^\s*{//; if ($s =~ s/^\s*\\//) { $continuation = 1; } if ($s =~ s/^\s*?\n//) { $check = 1; $cond_lines++; } # Also ignore a loop construct at the end of a # preprocessor statement. if (($prevline =~ /^.\s*#\s*define\s/ || $prevline =~ /\\\s*$/) && $continuation == 0) { $check = 0; } my $cond_ptr = -1; $continuation = 0; while ($cond_ptr != $cond_lines) { $cond_ptr = $cond_lines; # If we see an #else/#elif then the code # is not linear. if ($s =~ /^\s*\#\s*(?:else|elif)/) { $check = 0; } # Ignore: # 1) blank lines, they should be at 0, # 2) preprocessor lines, and # 3) labels. if ($continuation || $s =~ /^\s*?\n/ || $s =~ /^\s*#\s*?/ || $s =~ /^\s*$Ident\s*:/) { $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0; if ($s =~ s/^.*?\n//) { $cond_lines++; } } } my (undef, $sindent) = line_stats("+" . $s); my $stat_real = raw_line($linenr, $cond_lines); # Check if either of these lines are modified, else # this is not this patch's fault. if (!defined($stat_real) || $stat !~ /^\+/ && $stat_real !~ /^\+/) { $check = 0; } if (defined($stat_real) && $cond_lines > 1) { $stat_real = "[...]\n$stat_real"; } #print "line<$line> prevline<$prevline> indent<$indent> sindent<$sindent> check<$check> continuation<$continuation> s<$s> cond_lines<$cond_lines> stat_real<$stat_real> stat<$stat>\n"; if ($check && (($sindent % 8) != 0 || ($sindent <= $indent && $s ne ''))) { WARN("SUSPECT_CODE_INDENT", "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n"); } } # Track the 'values' across context and added lines. my $opline = $line; $opline =~ s/^./ /; my ($curr_values, $curr_vars) = annotate_values($opline . "\n", $prev_values); $curr_values = $prev_values . $curr_values; if ($dbg_values) { my $outline = $opline; $outline =~ s/\t/ /g; print "$linenr > .$outline\n"; print "$linenr > $curr_values\n"; print "$linenr > $curr_vars\n"; } $prev_values = substr($curr_values, -1); #ignore lines not being added if ($line=~/^[^\+]/) {next;} # TEST: allow direct testing of the type matcher. if ($dbg_type) { if ($line =~ /^.\s*$Declare\s*$/) { ERROR("TEST_TYPE", "TEST: is type\n" . $herecurr); } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) { ERROR("TEST_NOT_TYPE", "TEST: is not type ($1 is)\n". $herecurr); } next; } # TEST: allow direct testing of the attribute matcher. if ($dbg_attr) { if ($line =~ /^.\s*$Modifier\s*$/) { ERROR("TEST_ATTR", "TEST: is attr\n" . $herecurr); } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) { ERROR("TEST_NOT_ATTR", "TEST: is not attr ($1 is)\n". $herecurr); } next; } # check for initialisation to aggregates open brace on the next line if ($line =~ /^.\s*{/ && $prevline =~ /(?:^|[^=])=\s*$/) { ERROR("OPEN_BRACE", "that open brace { should be on the previous line\n" . $hereprev); } # # Checks which are anchored on the added line. # # check for malformed paths in #include statements (uses RAW line) if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) { my $path = $1; if ($path =~ m{//}) { ERROR("MALFORMED_INCLUDE", "malformed #include filename\n" . $herecurr); } } # no C99 // comments if ($line =~ m{//}) { ERROR("C99_COMMENTS", "do not use C99 // comments\n" . $herecurr); } # Remove C99 comments. $line =~ s@//.*@@; $opline =~ s@//.*@@; # EXPORT_SYMBOL should immediately follow the thing it is exporting, consider # the whole statement. #print "APW <$lines[$realline_next - 1]>\n"; if (defined $realline_next && exists $lines[$realline_next - 1] && !defined $suppress_export{$realline_next} && ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ || $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) { # Handle definitions which produce identifiers with # a prefix: # XXX(foo); # EXPORT_SYMBOL(something_foo); my $name = $1; if ($stat =~ /^.([A-Z_]+)\s*\(\s*($Ident)/ && $name =~ /^${Ident}_$2/) { #print "FOO C name<$name>\n"; $suppress_export{$realline_next} = 1; } elsif ($stat !~ /(?: \n.}\s*$| ^.DEFINE_$Ident\(\Q$name\E\)| ^.DECLARE_$Ident\(\Q$name\E\)| ^.LIST_HEAD\(\Q$name\E\)| ^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(| \b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\() )/x) { #print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n"; $suppress_export{$realline_next} = 2; } else { $suppress_export{$realline_next} = 1; } } if (!defined $suppress_export{$linenr} && $prevline =~ /^.\s*$/ && ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ || $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) { #print "FOO B <$lines[$linenr - 1]>\n"; $suppress_export{$linenr} = 2; } if (defined $suppress_export{$linenr} && $suppress_export{$linenr} == 2) { WARN("EXPORT_SYMBOL", "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr); } # check for global initialisers. if ($line =~ /^.$Type\s*$Ident\s*(?:\s+$Modifier)*\s*=\s*(0|NULL|false)\s*;/) { ERROR("GLOBAL_INITIALISERS", "do not initialise globals to 0 or NULL\n" . $herecurr); } # check for static initialisers. if ($line =~ /\bstatic\s.*=\s*(0|NULL|false)\s*;/) { ERROR("INITIALISED_STATIC", "do not initialise statics to 0 or NULL\n" . $herecurr); } # check for static const char * arrays. if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) { WARN("STATIC_CONST_CHAR_ARRAY", "static const char * array should probably be static const char * const\n" . $herecurr); } # check for static char foo[] = "bar" declarations. if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) { WARN("STATIC_CONST_CHAR_ARRAY", "static char array declaration should probably be static const char\n" . $herecurr); } # check for declarations of struct pci_device_id if ($line =~ /\bstruct\s+pci_device_id\s+\w+\s*\[\s*\]\s*\=\s*\{/) { WARN("DEFINE_PCI_DEVICE_TABLE", "Use DEFINE_PCI_DEVICE_TABLE for struct pci_device_id\n" . $herecurr); } # check for new typedefs, only function parameters and sparse annotations # make sense. if ($line =~ /\btypedef\s/ && $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ && $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ && $line !~ /\b$typeTypedefs\b/ && $line !~ /\b__bitwise(?:__|)\b/) { WARN("NEW_TYPEDEFS", "do not add new typedefs\n" . $herecurr); } # * goes on variable not on type # (char*[ const]) if ($line =~ m{\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\)}) { my ($from, $to) = ($1, $1); # Should start with a space. $to =~ s/^(\S)/ $1/; # Should not end with a space. $to =~ s/\s+$//; # '*'s should not have spaces between. while ($to =~ s/\*\s+\*/\*\*/) { } #print "from<$from> to<$to>\n"; if ($from ne $to) { ERROR("POINTER_LOCATION", "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr); } } elsif ($line =~ m{\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident)}) { my ($from, $to, $ident) = ($1, $1, $2); # Should start with a space. $to =~ s/^(\S)/ $1/; # Should not end with a space. $to =~ s/\s+$//; # '*'s should not have spaces between. while ($to =~ s/\*\s+\*/\*\*/) { } # Modifiers should have spaces. $to =~ s/(\b$Modifier$)/$1 /; #print "from<$from> to<$to> ident<$ident>\n"; if ($from ne $to && $ident !~ /^$Modifier$/) { ERROR("POINTER_LOCATION", "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr); } } # # no BUG() or BUG_ON() # if ($line =~ /\b(BUG|BUG_ON)\b/) { # print "Try to use WARN_ON & Recovery code rather than BUG() or BUG_ON()\n"; # print "$herecurr"; # $clean = 0; # } if ($line =~ /\bLINUX_VERSION_CODE\b/) { WARN("LINUX_VERSION_CODE", "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr); } # check for uses of printk_ratelimit if ($line =~ /\bprintk_ratelimit\s*\(/) { WARN("PRINTK_RATELIMITED", "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr); } # printk should use KERN_* levels. Note that follow on printk's on the # same line do not need a level, so we use the current block context # to try and find and validate the current printk. In summary the current # printk includes all preceding printk's which have no newline on the end. # we assume the first bad printk is the one to report. if ($line =~ /\bprintk\((?!KERN_)\s*"/) { my $ok = 0; for (my $ln = $linenr - 1; $ln >= $first_line; $ln--) { #print "CHECK<$lines[$ln - 1]\n"; # we have a preceding printk if it ends # with "\n" ignore it, else it is to blame if ($lines[$ln - 1] =~ m{\bprintk\(}) { if ($rawlines[$ln - 1] !~ m{\\n"}) { $ok = 1; } last; } } if ($ok == 0) { WARN("PRINTK_WITHOUT_KERN_LEVEL", "printk() should include KERN_ facility level\n" . $herecurr); } } # function brace can't be on same line, except for #defines of do while, # or if closed on same line if (($line=~/$Type\s*$Ident\(.*\).*\s{/) and !($line=~/\#\s*define.*do\s{/) and !($line=~/}/)) { ERROR("OPEN_BRACE", "open brace '{' following function declarations go on the next line\n" . $herecurr); } # open braces for enum, union and struct go on the same line. if ($line =~ /^.\s*{/ && $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) { ERROR("OPEN_BRACE", "open brace '{' following $1 go on the same line\n" . $hereprev); } # missing space after union, struct or enum definition if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?(?:\s+$Ident)?[=\{]/) { WARN("SPACING", "missing space after $1 definition\n" . $herecurr); } # check for spacing round square brackets; allowed: # 1. with a type on the left -- int [] a; # 2. at the beginning of a line for slice initialisers -- [0...10] = 5, # 3. inside a curly brace -- = { [0...10] = 5 } while ($line =~ /(.*?\s)\[/g) { my ($where, $prefix) = ($-[1], $1); if ($prefix !~ /$Type\s+$/ && ($where != 0 || $prefix !~ /^.\s+$/) && $prefix !~ /{\s+$/) { ERROR("BRACKET_SPACE", "space prohibited before open square bracket '['\n" . $herecurr); } } # check for spaces between functions and their parentheses. while ($line =~ /($Ident)\s+\(/g) { my $name = $1; my $ctx_before = substr($line, 0, $-[1]); my $ctx = "$ctx_before$name"; # Ignore those directives where spaces _are_ permitted. if ($name =~ /^(?: if|for|while|switch|return|case| volatile|__volatile__| __attribute__|format|__extension__| asm|__asm__)$/x) { # cpp #define statements have non-optional spaces, ie # if there is a space between the name and the open # parenthesis it is simply not a parameter group. } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) { # cpp #elif statement condition may start with a ( } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) { # If this whole things ends with a type its most # likely a typedef for a function. } elsif ($ctx =~ /$Type$/) { } else { WARN("SPACING", "space prohibited between function name and open parenthesis '('\n" . $herecurr); } } # Check operator spacing. if (!($line=~/\#\s*include/)) { my $ops = qr{ <<=|>>=|<=|>=|==|!=| \+=|-=|\*=|\/=|%=|\^=|\|=|&=| =>|->|<<|>>|<|>|=|!|~| &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%| \?|: }x; my @elements = split(/($ops|;)/, $opline); my $off = 0; my $blank = copy_spacing($opline); for (my $n = 0; $n < $#elements; $n += 2) { $off += length($elements[$n]); # Pick up the preceding and succeeding characters. my $ca = substr($opline, 0, $off); my $cc = ''; if (length($opline) >= ($off + length($elements[$n + 1]))) { $cc = substr($opline, $off + length($elements[$n + 1])); } my $cb = "$ca$;$cc"; my $a = ''; $a = 'V' if ($elements[$n] ne ''); $a = 'W' if ($elements[$n] =~ /\s$/); $a = 'C' if ($elements[$n] =~ /$;$/); $a = 'B' if ($elements[$n] =~ /(\[|\()$/); $a = 'O' if ($elements[$n] eq ''); $a = 'E' if ($ca =~ /^\s*$/); my $op = $elements[$n + 1]; my $c = ''; if (defined $elements[$n + 2]) { $c = 'V' if ($elements[$n + 2] ne ''); $c = 'W' if ($elements[$n + 2] =~ /^\s/); $c = 'C' if ($elements[$n + 2] =~ /^$;/); $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/); $c = 'O' if ($elements[$n + 2] eq ''); $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/); } else { $c = 'E'; } my $ctx = "${a}x${c}"; my $at = "(ctx:$ctx)"; my $ptr = substr($blank, 0, $off) . "^"; my $hereptr = "$hereline$ptr\n"; # Pull out the value of this operator. my $op_type = substr($curr_values, $off + 1, 1); # Get the full operator variant. my $opv = $op . substr($curr_vars, $off, 1); # Ignore operators passed as parameters. if ($op_type ne 'V' && $ca =~ /\s$/ && $cc =~ /^\s*,/) { # # Ignore comments # } elsif ($op =~ /^$;+$/) { # ; should have either the end of line or a space or \ after it } elsif ($op eq ';') { if ($ctx !~ /.x[WEBC]/ && $cc !~ /^\\/ && $cc !~ /^;/) { ERROR("SPACING", "space required after that '$op' $at\n" . $hereptr); } # // is a comment } elsif ($op eq '//') { # No spaces for: # -> # : when part of a bitfield } elsif ($op eq '->' || $opv eq ':B') { if ($ctx =~ /Wx.|.xW/) { ERROR("SPACING", "spaces prohibited around that '$op' $at\n" . $hereptr); } # , must have a space on the right. } elsif ($op eq ',') { if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) { ERROR("SPACING", "space required after that '$op' $at\n" . $hereptr); } # '*' as part of a type definition -- reported already. } elsif ($opv eq '*_') { #warn "'*' is part of type\n"; # unary operators should have a space before and # none after. May be left adjacent to another # unary operator, or a cast } elsif ($op eq '!' || $op eq '~' || $opv eq '*U' || $opv eq '-U' || $opv eq '&U' || $opv eq '&&U') { if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) { ERROR("SPACING", "space required before that '$op' $at\n" . $hereptr); } if ($op eq '*' && $cc =~/\s*$Modifier\b/) { # A unary '*' may be const } elsif ($ctx =~ /.xW/) { ERROR("SPACING", "space prohibited after that '$op' $at\n" . $hereptr); } # unary ++ and unary -- are allowed no space on one side. } elsif ($op eq '++' or $op eq '--') { if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) { ERROR("SPACING", "space required one side of that '$op' $at\n" . $hereptr); } if ($ctx =~ /Wx[BE]/ || ($ctx =~ /Wx./ && $cc =~ /^;/)) { ERROR("SPACING", "space prohibited before that '$op' $at\n" . $hereptr); } if ($ctx =~ /ExW/) { ERROR("SPACING", "space prohibited after that '$op' $at\n" . $hereptr); } # << and >> may either have or not have spaces both sides } elsif ($op eq '<<' or $op eq '>>' or $op eq '&' or $op eq '^' or $op eq '|' or $op eq '+' or $op eq '-' or $op eq '*' or $op eq '/' or $op eq '%') { if ($ctx =~ /Wx[^WCE]|[^WCE]xW/) { ERROR("SPACING", "need consistent spacing around '$op' $at\n" . $hereptr); } # A colon needs no spaces before when it is # terminating a case value or a label. } elsif ($opv eq ':C' || $opv eq ':L') { if ($ctx =~ /Wx./) { ERROR("SPACING", "space prohibited before that '$op' $at\n" . $hereptr); } # All the others need spaces both sides. } elsif ($ctx !~ /[EWC]x[CWE]/) { my $ok = 0; # Ignore email addresses <foo@bar> if (($op eq '<' && $cc =~ /^\S+\@\S+>/) || ($op eq '>' && $ca =~ /<\S+\@\S+$/)) { $ok = 1; } # Ignore ?: if (($opv eq ':O' && $ca =~ /\?$/) || ($op eq '?' && $cc =~ /^:/)) { $ok = 1; } if ($ok == 0) { ERROR("SPACING", "spaces required around that '$op' $at\n" . $hereptr); } } $off += length($elements[$n + 1]); } } # check for multiple assignments if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) { CHK("MULTIPLE_ASSIGNMENTS", "multiple assignments should be avoided\n" . $herecurr); } ## # check for multiple declarations, allowing for a function declaration ## # continuation. ## if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ && ## $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) { ## ## # Remove any bracketed sections to ensure we do not ## # falsly report the parameters of functions. ## my $ln = $line; ## while ($ln =~ s/\([^\(\)]*\)//g) { ## } ## if ($ln =~ /,/) { ## WARN("MULTIPLE_DECLARATION", ## "declaring multiple variables together should be avoided\n" . $herecurr); ## } ## } #need space before brace following if, while, etc if (($line =~ /\(.*\){/ && $line !~ /\($Type\){/) || $line =~ /do{/) { ERROR("SPACING", "space required before the open brace '{'\n" . $herecurr); } # closing brace should have a space following it when it has anything # on the line if ($line =~ /}(?!(?:,|;|\)))\S/) { ERROR("SPACING", "space required after that close brace '}'\n" . $herecurr); } # check spacing on square brackets if ($line =~ /\[\s/ && $line !~ /\[\s*$/) { ERROR("SPACING", "space prohibited after that open square bracket '['\n" . $herecurr); } if ($line =~ /\s\]/) { ERROR("SPACING", "space prohibited before that close square bracket ']'\n" . $herecurr); } # check spacing on parentheses if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ && $line !~ /for\s*\(\s+;/) { ERROR("SPACING", "space prohibited after that open parenthesis '('\n" . $herecurr); } if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ && $line !~ /for\s*\(.*;\s+\)/ && $line !~ /:\s+\)/) { ERROR("SPACING", "space prohibited before that close parenthesis ')'\n" . $herecurr); } #goto labels aren't indented, allow a single space however if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) { WARN("INDENTED_LABEL", "labels should not be indented\n" . $herecurr); } # Return is not a function. if (defined($stat) && $stat =~ /^.\s*return(\s*)(\(.*);/s) { my $spacing = $1; my $value = $2; # Flatten any parentheses $value =~ s/\(/ \(/g; $value =~ s/\)/\) /g; while ($value =~ s/\[[^\{\}]*\]/1/ || $value !~ /(?:$Ident|-?$Constant)\s* $Compare\s* (?:$Ident|-?$Constant)/x && $value =~ s/\([^\(\)]*\)/1/) { } #print "value<$value>\n"; if ($value =~ /^\s*(?:$Ident|-?$Constant)\s*$/) { ERROR("RETURN_PARENTHESES", "return is not a function, parentheses are not required\n" . $herecurr); } elsif ($spacing !~ /\s+/) { ERROR("SPACING", "space required before the open parenthesis '('\n" . $herecurr); } } # Return of what appears to be an errno should normally be -'ve if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) { my $name = $1; if ($name ne 'EOF' && $name ne 'ERROR') { WARN("USE_NEGATIVE_ERRNO", "return of an errno should typically be -ve (return -$1)\n" . $herecurr); } } # typecasts on min/max could be min_t/max_t if ($line =~ /^\+(?:.*?)\b(min|max)\s*\($Typecast{0,1}($LvalOrFunc)\s*,\s*$Typecast{0,1}($LvalOrFunc)\s*\)/) { if (defined $2 || defined $8) { my $call = $1; my $cast1 = deparenthesize($2); my $arg1 = $3; my $cast2 = deparenthesize($8); my $arg2 = $9; my $cast; if ($cast1 ne "" && $cast2 ne "") { $cast = "$cast1 or $cast2"; } elsif ($cast1 ne "") { $cast = $cast1; } else { $cast = $cast2; } WARN("MINMAX", "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . $herecurr); } } # Need a space before open parenthesis after if, while etc if ($line=~/\b(if|while|for|switch)\(/) { ERROR("SPACING", "space required before the open parenthesis '('\n" . $herecurr); } # Check for illegal assignment in if conditional -- and check for trailing # statements after the conditional. if ($line =~ /do\s*(?!{)/) { my ($stat_next) = ctx_statement_block($line_nr_next, $remain_next, $off_next); $stat_next =~ s/\n./\n /g; ##print "stat<$stat> stat_next<$stat_next>\n"; if ($stat_next =~ /^\s*while\b/) { # If the statement carries leading newlines, # then count those as offsets. my ($whitespace) = ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s); my $offset = statement_rawlines($whitespace) - 1; $suppress_whiletrailers{$line_nr_next + $offset} = 1; } } if (!defined $suppress_whiletrailers{$linenr} && $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) { my ($s, $c) = ($stat, $cond); if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) { ERROR("ASSIGN_IN_IF", "do not use assignment in if condition\n" . $herecurr); } # Find out what is on the end of the line after the # conditional. substr($s, 0, length($c), ''); $s =~ s/\n.*//g; $s =~ s/$;//g; # Remove any comments if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ && $c !~ /}\s*while\s*/) { # Find out how long the conditional actually is. my @newlines = ($c =~ /\n/gs); my $cond_lines = 1 + $#newlines; my $stat_real = ''; $stat_real = raw_line($linenr, $cond_lines) . "\n" if ($cond_lines); if (defined($stat_real) && $cond_lines > 1) { $stat_real = "[...]\n$stat_real"; } ERROR("TRAILING_STATEMENTS", "trailing statements should be on next line\n" . $herecurr . $stat_real); } } # Check for bitwise tests written as boolean if ($line =~ / (?: (?:\[|\(|\&\&|\|\|) \s*0[xX][0-9]+\s* (?:\&\&|\|\|) | (?:\&\&|\|\|) \s*0[xX][0-9]+\s* (?:\&\&|\|\||\)|\]) )/x) { WARN("HEXADECIMAL_BOOLEAN_TEST", "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr); } # if and else should not have general statements after it if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) { my $s = $1; $s =~ s/$;//g; # Remove any comments if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) { ERROR("TRAILING_STATEMENTS", "trailing statements should be on next line\n" . $herecurr); } } # if should not continue a brace if ($line =~ /}\s*if\b/) { ERROR("TRAILING_STATEMENTS", "trailing statements should be on next line\n" . $herecurr); } # case and default should not have general statements after them if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g && $line !~ /\G(?: (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$| \s*return\s+ )/xg) { ERROR("TRAILING_STATEMENTS", "trailing statements should be on next line\n" . $herecurr); } # Check for }<nl>else {, these must be at the same # indent level to be relevant to each other. if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ and $previndent == $indent) { ERROR("ELSE_AFTER_BRACE", "else should follow close brace '}'\n" . $hereprev); } if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ and $previndent == $indent) { my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0); # Find out what is on the end of the line after the # conditional. substr($s, 0, length($c), ''); $s =~ s/\n.*//g; if ($s =~ /^\s*;/) { ERROR("WHILE_AFTER_BRACE", "while should follow close brace '}'\n" . $hereprev); } } #studly caps, commented out until figure out how to distinguish between use of existing and adding new # if (($line=~/[\w_][a-z\d]+[A-Z]/) and !($line=~/print/)) { # print "No studly caps, use _\n"; # print "$herecurr"; # $clean = 0; # } #no spaces allowed after \ in define if ($line=~/\#\s*define.*\\\s$/) { WARN("WHITESPACE_AFTER_LINE_CONTINUATION", "Whitepspace after \\ makes next lines useless\n" . $herecurr); } #warn if <asm/foo.h> is #included and <linux/foo.h> is available (uses RAW line) if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) { my $file = "$1.h"; my $checkfile = "include/linux/$file"; if (-f "$root/$checkfile" && $realfile ne $checkfile && $1 !~ /$allowed_asm_includes/) { if ($realfile =~ m{^arch/}) { CHK("ARCH_INCLUDE_LINUX", "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr); } else { WARN("INCLUDE_LINUX", "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr); } } } # multi-statement macros should be enclosed in a do while loop, grab the # first statement and ensure its the whole macro if its not enclosed # in a known good container if ($realfile !~ m@/vmlinux.lds.h$@ && $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) { my $ln = $linenr; my $cnt = $realcnt; my ($off, $dstat, $dcond, $rest); my $ctx = ''; my $args = defined($1); # Find the end of the macro and limit our statement # search to that. while ($cnt > 0 && defined $lines[$ln - 1] && $lines[$ln - 1] =~ /^(?:-|..*\\$)/) { $ctx .= $rawlines[$ln - 1] . "\n"; $cnt-- if ($lines[$ln - 1] !~ /^-/); $ln++; } $ctx .= $rawlines[$ln - 1]; ($dstat, $dcond, $ln, $cnt, $off) = ctx_statement_block($linenr, $ln - $linenr + 1, 0); #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n"; #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n"; # Extract the remainder of the define (if any) and # rip off surrounding spaces, and trailing \'s. $rest = ''; while ($off != 0 || ($cnt > 0 && $rest =~ /\\\s*$/)) { #print "ADDING cnt<$cnt> $off <" . substr($lines[$ln - 1], $off) . "> rest<$rest>\n"; if ($off != 0 || $lines[$ln - 1] !~ /^-/) { $rest .= substr($lines[$ln - 1], $off) . "\n"; $cnt--; } $ln++; $off = 0; } $rest =~ s/\\\n.//g; $rest =~ s/^\s*//s; $rest =~ s/\s*$//s; # Clean up the original statement. if ($args) { substr($dstat, 0, length($dcond), ''); } else { $dstat =~ s/^.\s*\#\s*define\s+$Ident\s*//; } $dstat =~ s/$;//g; $dstat =~ s/\\\n.//g; $dstat =~ s/^\s*//s; $dstat =~ s/\s*$//s; # Flatten any parentheses and braces while ($dstat =~ s/\([^\(\)]*\)/1/ || $dstat =~ s/\{[^\{\}]*\}/1/ || $dstat =~ s/\[[^\{\}]*\]/1/) { } my $exceptions = qr{ $Declare| module_param_named| MODULE_PARAM_DESC| DECLARE_PER_CPU| DEFINE_PER_CPU| __typeof__\(| union| struct| \.$Ident\s*=\s*| ^\"|\"$ }x; #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n"; if ($rest ne '' && $rest ne ',') { if ($rest !~ /while\s*\(/ && $dstat !~ /$exceptions/) { ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE", "Macros with multiple statements should be enclosed in a do - while loop\n" . "$here\n$ctx\n"); } } elsif ($ctx !~ /;/) { if ($dstat ne '' && $dstat !~ /^(?:$Ident|-?$Constant)$/ && $dstat !~ /$exceptions/ && $dstat !~ /^\.$Ident\s*=/ && $dstat =~ /$Operators/) { ERROR("COMPLEX_MACRO", "Macros with complex values should be enclosed in parenthesis\n" . "$here\n$ctx\n"); } } } # make sure symbols are always wrapped with VMLINUX_SYMBOL() ... # all assignments may have only one of the following with an assignment: # . # ALIGN(...) # VMLINUX_SYMBOL(...) if ($realfile eq 'vmlinux.lds.h' && $line =~ /(?:(?:^|\s)$Ident\s*=|=\s*$Ident(?:\s|$))/) { WARN("MISSING_VMLINUX_SYMBOL", "vmlinux.lds.h needs VMLINUX_SYMBOL() around C-visible symbols\n" . $herecurr); } # check for redundant bracing round if etc if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) { my ($level, $endln, @chunks) = ctx_statement_full($linenr, $realcnt, 1); #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n"; #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n"; if ($#chunks > 0 && $level == 0) { my $allowed = 0; my $seen = 0; my $herectx = $here . "\n"; my $ln = $linenr - 1; for my $chunk (@chunks) { my ($cond, $block) = @{$chunk}; # If the condition carries leading newlines, then count those as offsets. my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s); my $offset = statement_rawlines($whitespace) - 1; #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n"; # We have looked at and allowed this specific line. $suppress_ifbraces{$ln + $offset} = 1; $herectx .= "$rawlines[$ln + $offset]\n[...]\n"; $ln += statement_rawlines($block) - 1; substr($block, 0, length($cond), ''); $seen++ if ($block =~ /^\s*{/); #print "cond<$cond> block<$block> allowed<$allowed>\n"; if (statement_lines($cond) > 1) { #print "APW: ALLOWED: cond<$cond>\n"; $allowed = 1; } if ($block =~/\b(?:if|for|while)\b/) { #print "APW: ALLOWED: block<$block>\n"; $allowed = 1; } if (statement_block_size($block) > 1) { #print "APW: ALLOWED: lines block<$block>\n"; $allowed = 1; } } if ($seen && !$allowed) { WARN("BRACES", "braces {} are not necessary for any arm of this statement\n" . $herectx); } } } if (!defined $suppress_ifbraces{$linenr - 1} && $line =~ /\b(if|while|for|else)\b/) { my $allowed = 0; # Check the pre-context. if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) { #print "APW: ALLOWED: pre<$1>\n"; $allowed = 1; } my ($level, $endln, @chunks) = ctx_statement_full($linenr, $realcnt, $-[0]); # Check the condition. my ($cond, $block) = @{$chunks[0]}; #print "CHECKING<$linenr> cond<$cond> block<$block>\n"; if (defined $cond) { substr($block, 0, length($cond), ''); } if (statement_lines($cond) > 1) { #print "APW: ALLOWED: cond<$cond>\n"; $allowed = 1; } if ($block =~/\b(?:if|for|while)\b/) { #print "APW: ALLOWED: block<$block>\n"; $allowed = 1; } if (statement_block_size($block) > 1) { #print "APW: ALLOWED: lines block<$block>\n"; $allowed = 1; } # Check the post-context. if (defined $chunks[1]) { my ($cond, $block) = @{$chunks[1]}; if (defined $cond) { substr($block, 0, length($cond), ''); } if ($block =~ /^\s*\{/) { #print "APW: ALLOWED: chunk-1 block<$block>\n"; $allowed = 1; } } if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) { my $herectx = $here . "\n";; my $cnt = statement_rawlines($block); for (my $n = 0; $n < $cnt; $n++) { $herectx .= raw_line($linenr, $n) . "\n";; } WARN("BRACES", "braces {} are not necessary for single statement blocks\n" . $herectx); } } # don't include deprecated include files (uses RAW line) for my $inc (@dep_includes) { if ($rawline =~ m@^.\s*\#\s*include\s*\<$inc>@) { ERROR("DEPRECATED_INCLUDE", "Don't use <$inc>: see Documentation/feature-removal-schedule.txt\n" . $herecurr); } } # don't use deprecated functions for my $func (@dep_functions) { if ($line =~ /\b$func\b/) { ERROR("DEPRECATED_FUNCTION", "Don't use $func(): see Documentation/feature-removal-schedule.txt\n" . $herecurr); } } # no volatiles please my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b}; if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) { WARN("VOLATILE", "Use of volatile is usually wrong: see Documentation/volatile-considered-harmful.txt\n" . $herecurr); } # warn about #if 0 if ($line =~ /^.\s*\#\s*if\s+0\b/) { CHK("REDUNDANT_CODE", "if this code is redundant consider removing it\n" . $herecurr); } # check for needless kfree() checks if ($prevline =~ /\bif\s*\(([^\)]*)\)/) { my $expr = $1; if ($line =~ /\bkfree\(\Q$expr\E\);/) { WARN("NEEDLESS_KFREE", "kfree(NULL) is safe this check is probably not required\n" . $hereprev); } } # check for needless usb_free_urb() checks if ($prevline =~ /\bif\s*\(([^\)]*)\)/) { my $expr = $1; if ($line =~ /\busb_free_urb\(\Q$expr\E\);/) { WARN("NEEDLESS_USB_FREE_URB", "usb_free_urb(NULL) is safe this check is probably not required\n" . $hereprev); } } # prefer usleep_range over udelay if ($line =~ /\budelay\s*\(\s*(\w+)\s*\)/) { # ignore udelay's < 10, however if (! (($1 =~ /(\d+)/) && ($1 < 10)) ) { CHK("USLEEP_RANGE", "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.txt\n" . $line); } } # warn about unexpectedly long msleep's if ($line =~ /\bmsleep\s*\((\d+)\);/) { if ($1 < 20) { WARN("MSLEEP", "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.txt\n" . $line); } } # warn about #ifdefs in C files # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) { # print "#ifdef in C files should be avoided\n"; # print "$herecurr"; # $clean = 0; # } # warn about spacing in #ifdefs if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) { ERROR("SPACING", "exactly one space required after that #$1\n" . $herecurr); } # check for spinlock_t definitions without a comment. if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ || $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) { my $which = $1; if (!ctx_has_comment($first_line, $linenr)) { CHK("UNCOMMENTED_DEFINITION", "$1 definition without comment\n" . $herecurr); } } # check for memory barriers without a comment. if ($line =~ /\b(mb|rmb|wmb|read_barrier_depends|smp_mb|smp_rmb|smp_wmb|smp_read_barrier_depends)\(/) { if (!ctx_has_comment($first_line, $linenr)) { CHK("MEMORY_BARRIER", "memory barrier without comment\n" . $herecurr); } } # check of hardware specific defines if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) { CHK("ARCH_DEFINES", "architecture specific defines should be avoided\n" . $herecurr); } # Check that the storage class is at the beginning of a declaration if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) { WARN("STORAGE_CLASS", "storage class should be at the beginning of the declaration\n" . $herecurr) } # check the location of the inline attribute, that it is between # storage class and type. if ($line =~ /\b$Type\s+$Inline\b/ || $line =~ /\b$Inline\s+$Storage\b/) { ERROR("INLINE_LOCATION", "inline keyword should sit between storage class and type\n" . $herecurr); } # Check for __inline__ and __inline, prefer inline if ($line =~ /\b(__inline__|__inline)\b/) { WARN("INLINE", "plain inline is preferred over $1\n" . $herecurr); } # Check for __attribute__ packed, prefer __packed if ($line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) { WARN("PREFER_PACKED", "__packed is preferred over __attribute__((packed))\n" . $herecurr); } # Check for __attribute__ aligned, prefer __aligned if ($line =~ /\b__attribute__\s*\(\s*\(.*aligned/) { WARN("PREFER_ALIGNED", "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr); } # check for sizeof(&) if ($line =~ /\bsizeof\s*\(\s*\&/) { WARN("SIZEOF_ADDRESS", "sizeof(& should be avoided\n" . $herecurr); } # check for line continuations in quoted strings with odd counts of " if ($rawline =~ /\\$/ && $rawline =~ tr/"/"/ % 2) { WARN("LINE_CONTINUATIONS", "Avoid line continuations in quoted strings\n" . $herecurr); } # check for new externs in .c files. if ($realfile =~ /\.c$/ && defined $stat && $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s) { my $function_name = $1; my $paren_space = $2; my $s = $stat; if (defined $cond) { substr($s, 0, length($cond), ''); } if ($s =~ /^\s*;/ && $function_name ne 'uninitialized_var') { WARN("AVOID_EXTERNS", "externs should be avoided in .c files\n" . $herecurr); } if ($paren_space =~ /\n/) { WARN("FUNCTION_ARGUMENTS", "arguments for function declarations should follow identifier\n" . $herecurr); } } elsif ($realfile =~ /\.c$/ && defined $stat && $stat =~ /^.\s*extern\s+/) { WARN("AVOID_EXTERNS", "externs should be avoided in .c files\n" . $herecurr); } # checks for new __setup's if ($rawline =~ /\b__setup\("([^"]*)"/) { my $name = $1; if (!grep(/$name/, @setup_docs)) { CHK("UNDOCUMENTED_SETUP", "__setup appears un-documented -- check Documentation/kernel-parameters.txt\n" . $herecurr); } } # check for pointless casting of kmalloc return if ($line =~ /\*\s*\)\s*[kv][czm]alloc(_node){0,1}\b/) { WARN("UNNECESSARY_CASTS", "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr); } # check for multiple semicolons if ($line =~ /;\s*;\s*$/) { WARN("ONE_SEMICOLON", "Statements terminations use 1 semicolon\n" . $herecurr); } # check for gcc specific __FUNCTION__ if ($line =~ /__FUNCTION__/) { WARN("USE_FUNC", "__func__ should be used instead of gcc specific __FUNCTION__\n" . $herecurr); } # check for semaphores initialized locked if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) { WARN("CONSIDER_COMPLETION", "consider using a completion\n" . $herecurr); } # recommend kstrto* over simple_strto* if ($line =~ /\bsimple_(strto.*?)\s*\(/) { WARN("CONSIDER_KSTRTO", "consider using kstrto* in preference to simple_$1\n" . $herecurr); } # check for __initcall(), use device_initcall() explicitly please if ($line =~ /^.\s*__initcall\s*\(/) { WARN("USE_DEVICE_INITCALL", "please use device_initcall() instead of __initcall()\n" . $herecurr); } # check for various ops structs, ensure they are const. my $struct_ops = qr{acpi_dock_ops| address_space_operations| backlight_ops| block_device_operations| dentry_operations| dev_pm_ops| dma_map_ops| extent_io_ops| file_lock_operations| file_operations| hv_ops| ide_dma_ops| intel_dvo_dev_ops| item_operations| iwl_ops| kgdb_arch| kgdb_io| kset_uevent_ops| lock_manager_operations| microcode_ops| mtrr_ops| neigh_ops| nlmsvc_binding| pci_raw_ops| pipe_buf_operations| platform_hibernation_ops| platform_suspend_ops| proto_ops| rpc_pipe_ops| seq_operations| snd_ac97_build_ops| soc_pcmcia_socket_ops| stacktrace_ops| sysfs_ops| tty_operations| usb_mon_operations| wd_ops}x; if ($line !~ /\bconst\b/ && $line =~ /\bstruct\s+($struct_ops)\b/) { WARN("CONST_STRUCT", "struct $1 should normally be const\n" . $herecurr); } # use of NR_CPUS is usually wrong # ignore definitions of NR_CPUS and usage to define arrays as likely right if ($line =~ /\bNR_CPUS\b/ && $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ && $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ && $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ && $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ && $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/) { WARN("NR_CPUS", "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr); } # check for %L{u,d,i} in strings my $string; while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) { $string = substr($rawline, $-[1], $+[1] - $-[1]); $string =~ s/%%/__/g; if ($string =~ /(?<!%)%L[udi]/) { WARN("PRINTF_L", "\%Ld/%Lu are not-standard C, use %lld/%llu\n" . $herecurr); last; } } # whine mightly about in_atomic if ($line =~ /\bin_atomic\s*\(/) { if ($realfile =~ m@^drivers/@) { ERROR("IN_ATOMIC", "do not use in_atomic in drivers\n" . $herecurr); } elsif ($realfile !~ m@^kernel/@) { WARN("IN_ATOMIC", "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr); } } # check for lockdep_set_novalidate_class if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ || $line =~ /__lockdep_no_validate__\s*\)/ ) { if ($realfile !~ m@^kernel/lockdep@ && $realfile !~ m@^include/linux/lockdep@ && $realfile !~ m@^drivers/base/core@) { ERROR("LOCKDEP", "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr); } } if ($line =~ /debugfs_create_file.*S_IWUGO/ || $line =~ /DEVICE_ATTR.*S_IWUGO/ ) { WARN("EXPORTED_WORLD_WRITABLE", "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr); } # Check for memset with swapped arguments if ($line =~ /memset.*\,(\ |)(0x|)0(\ |0|)\);/) { ERROR("MEMSET", "memset size is 3rd argument, not the second.\n" . $herecurr); } } # If we have no input at all, then there is nothing to report on # so just keep quiet. if ($#rawlines == -1) { exit(0); } # In mailback mode only produce a report in the negative, for # things that appear to be patches. if ($mailback && ($clean == 1 || !$is_patch)) { exit(0); } # This is not a patch, and we are are in 'no-patch' mode so # just keep quiet. if (!$chk_patch && !$is_patch) { exit(0); } if (!$is_patch) { ERROR("NOT_UNIFIED_DIFF", "Does not appear to be a unified-diff format patch\n"); } if ($is_patch && $chk_signoff && $signoff == 0) { ERROR("MISSING_SIGN_OFF", "Missing Signed-off-by: line(s)\n"); } print report_dump(); if ($summary && !($clean == 1 && $quiet == 1)) { print "$filename " if ($summary_file); print "total: $cnt_error errors, $cnt_warn warnings, " . (($check)? "$cnt_chk checks, " : "") . "$cnt_lines lines checked\n"; print "\n" if ($quiet == 0); } if ($quiet == 0) { # If there were whitespace errors which cleanpatch can fix # then suggest that. if ($rpt_cleaners) { print "NOTE: whitespace errors detected, you may wish to use scripts/cleanpatch or\n"; print " scripts/cleanfile\n\n"; $rpt_cleaners = 0; } } if (keys %ignore_type) { print "NOTE: Ignored message types:"; foreach my $ignore (sort keys %ignore_type) { print " $ignore"; } print "\n"; print "\n" if ($quiet == 0); } if ($clean == 1 && $quiet == 0) { print "$vname has no obvious style problems and is ready for submission.\n" } if ($clean == 0 && $quiet == 0) { print << "EOM"; $vname has style problems, please review. If any of these errors are false positives, please report them to the maintainer, see CHECKPATCH in MAINTAINERS. EOM } return $clean; }
1001-study-uboot
tools/checkpatch.pl
Prolog
gpl3
90,324
#!/bin/sh # This script converts binary files (u-boot.bin) into so called # bootstrap records that are accepted by Motorola's MC9328MX1/L # (a.k.a. DragaonBall i.MX) in "Bootstrap Mode" # # The code for the SynchFlash programming routines is taken from # Bootloader\Bin\SyncFlash\programBoot_b.txt contained in # Motorolas LINUX_BSP_0_3_8.tar.gz # # The script could easily extended for AMD flash routines. # # 2004-06-23 - steven.scholz@imc-berlin.de ################################################################################# # From the posting to the U-Boot-Users mailing list, 23 Jun 2004: # =============================================================== # I just hacked a simple script that converts u-boot.bin into a text file # containg processor init code, SynchFlash programming code and U-Boot data in # form of so called b-records. # # This can be used to programm U-Boot into (Synch)Flash using the Bootstrap # Mode of the MC9328MX1/L # # 0AFE1F3410202E2E2E000000002073756363656564/ # 0AFE1F44102E0A0000206661696C656420210A0000/ # 0AFE100000 # ... # MX1ADS Sync-flash Programming Utility v0.5 2002/08/21 # # Source address (stored in 0x0AFE0000): 0x0A000000 # Target address (stored in 0x0AFE0004): 0x0C000000 # Size (stored in 0x0AFE0008): 0x0001A320 # # Press any key to start programming ... # Erasing ... # Blank checking ... # Programming ... # Verifying flash ... succeed. # # Programming finished. # # So no need for a BDI2000 anymore... ;-) # # This is working on my MX1ADS eval board. Hope this could be useful for # someone. ################################################################################# if [ "$#" -lt 1 -o "$#" -gt 2 ] ; then echo "Usage: $0 infile [outfile]" >&2 echo " $0 u-boot.bin [u-boot.brec]" >&2 exit 1 fi if [ "$#" -ge 1 ] ; then INFILE=$1 fi if [ ! -f $INFILE ] ; then echo "Error: file '$INFILE' does not exist." >&2 exit 1 fi FILESIZE=`filesize $INFILE` output_init() { echo "\ ******************************************** * Initialize I/O Pad Driving Strength * ******************************************** 0021B80CC4000003AB ******************************************** * Initialize SDRAM * ******************************************** 00221000C492120200 ; pre-charge command 08200000E4 ; special read 00221000C4A2120200 ; auto-refresh command 08000000E4 ; 8 special read 08000000E4 ; 8 special read 08000000E4 ; 8 special read 08000000E4 ; 8 special read 08000000E4 ; 8 special read 08000000E4 ; 8 special read 08000000E4 ; 8 special read 08000000E4 ; 8 special read 00221000C4B2120200 ; set mode register 08111800E4 ; special read 00221000C482124200 ; set normal mode " } output_uboot() { echo "\ ******************************************** * U-Boot image as bootstrap records * * will be stored in SDRAM at 0x0A000000 * ******************************************** " cat $INFILE | \ hexdump -v -e "\"0A0%05.5_ax10\" 16/1 \"%02x\"\"\r\n\"" | \ tr [:lower:] [:upper:] } output_flashprog() { echo "\ ******************************************** * Address of arguments to flashProg * * ---------------------------------------- * * Source : 0x0A000000 * * Destination : 0x0C000000 * " # get the real size of the U-Boot image printf "* Size : 0x%08X *\r\n" $FILESIZE printf "********************************************\r\n" printf "0AFE0000CC0A0000000C000000%08X\r\n" $FILESIZE #;0AFE0000CC0A0000000C00000000006000 echo "\ ******************************************** * Flash Program * ******************************************** 0AFE10001008D09FE5AC0000EA00F0A0E1A42DFE0A 0AFE1010100080FE0A0DC0A0E100D82DE904B04CE2 0AFE1020109820A0E318309FE5003093E5033082E0 0AFE103010003093E5013003E2FF3003E20300A0E1 0AFE10401000A81BE9A01DFE0A0DC0A0E100D82DE9 0AFE10501004B04CE204D04DE20030A0E10D304BE5 0AFE1060109820A0E330309FE5003093E5033082E0 0AFE107010003093E5013903E2000053E3F7FFFF0A 0AFE1080104020A0E310309FE5003093E5032082E0 0AFE1090100D305BE5003082E500A81BE9A01DFE0A 0AFE10A0100DC0A0E100D82DE904B04CE20000A0E1 0AFE10B010D7FFFFEB0030A0E1FF3003E2000053E3 0AFE10C010FAFFFF0A10309FE5003093E5003093E5 0AFE10D010FF3003E20300A0E100A81BE9A01DFE0A 0AFE10E0100DC0A0E100D82DE904B04CE204D04DE2 0AFE10F0100030A0E10D304BE50D305BE52332A0E1 0AFE1100100E304BE50E305BE5090053E30300009A 0AFE1110100E305BE5373083E20E304BE5020000EA 0AFE1120100E305BE5303083E20E304BE50E305BE5 0AFE1130100300A0E1C3FFFFEB0D305BE50F3003E2 0AFE1140100E304BE50E305BE5090053E30300009A 0AFE1150100E305BE5373083E20E304BE5020000EA 0AFE1160100E305BE5303083E20E304BE50E305BE5 0AFE1170100300A0E1B3FFFFEB00A81BE90DC0A0E1 0AFE11801000D82DE904B04CE21CD04DE210000BE5 0AFE11901014100BE518200BE588009FE5E50200EB 0AFE11A01010301BE51C300BE514301BE520300BE5 0AFE11B0100030A0E324300BE524201BE518301BE5 0AFE11C010030052E10000003A120000EA1C004BE2 0AFE11D010002090E520104BE2003091E500C093E5 0AFE11E010043083E2003081E5003092E5042082E2 0AFE11F010002080E50C0053E10200000A0030A0E3 0AFE12001028300BE5050000EA24301BE5043083E2 0AFE12101024300BE5E7FFFFEA0130A0E328300BE5 0AFE12201028001BE500A81BE9E81EFE0A0DC0A0E1 0AFE12301000D82DE904B04CE214D04DE210000BE5 0AFE12401014100BE56C009FE5BA0200EB10301BE5 0AFE12501018300BE50030A0E31C300BE51C201BE5 0AFE12601014301BE5030052E10000003A0D0000EA 0AFE12701018304BE2002093E5001092E5042082E2 0AFE128010002083E5010071E30200000A0030A0E3 0AFE12901020300BE5050000EA1C301BE5043083E2 0AFE12A0101C300BE5ECFFFFEA0130A0E320300BE5 0AFE12B01020001BE500A81BE9001FFE0A0DC0A0E1 0AFE12C01000D82DE904B04CE224D04DE20130A0E3 0AFE12D01024300BE5A4229FE58139A0E3023A83E2 0AFE12E010003082E59820A0E390329FE5003093E5 0AFE12F010033082E0003093E5023903E2000053E3 0AFE1300100300001A74229FE58139A0E3033A83E2 0AFE131010003082E568029FE5860200EBAF36A0E3 0AFE1320100E3883E2003093E510300BE554029FE5 0AFE133010800200EB10301BE5233CA0E1FF3003E2 0AFE1340100300A0E165FFFFEB10301BE52338A0E1 0AFE135010FF3003E20300A0E160FFFFEB10301BE5 0AFE1360102334A0E1FF3003E20300A0E15BFFFFEB 0AFE13701010305BE50300A0E158FFFFEB0A00A0E3 0AFE13801030FFFFEB0D00A0E32EFFFFEBAF36A0E3 0AFE1390100E3883E2043083E2003093E514300BE5 0AFE13A010E4019FE5630200EB14301BE5233CA0E1 0AFE13B010FF3003E20300A0E148FFFFEB14301BE5 0AFE13C0102338A0E1FF3003E20300A0E143FFFFEB 0AFE13D01014301BE52334A0E1FF3003E20300A0E1 0AFE13E0103EFFFFEB14305BE50300A0E13BFFFFEB 0AFE13F0100A00A0E313FFFFEB0D00A0E311FFFFEB 0AFE140010AF36A0E30E3883E2083083E2003093E5 0AFE14101018300BE574019FE5460200EB18301BE5 0AFE142010233CA0E1FF3003E20300A0E12BFFFFEB 0AFE14301018301BE52338A0E1FF3003E20300A0E1 0AFE14401026FFFFEB18301BE52334A0E1FF3003E2 0AFE1450100300A0E121FFFFEB18305BE50300A0E1 0AFE1460101EFFFFEB0A00A0E3F6FEFFEB0D00A0E3 0AFE147010F4FEFFEBE6FEFFEB0030A0E1FF3003E2 0AFE148010000053E30000001A020000EA03FFFFEB 0AFE1490102D004BE5F6FFFFEAF4009FE5250200EB 0AFE14A010FEFEFFEB2D004BE5CD0000EBC00000EB 0AFE14B010E0009FE51F0200EB18301BE528300BE5 0AFE14C01014301BE52C300BE52C001BE5100100EB 0AFE14D01028301BE5013643E228300BE52C301BE5 0AFE14E010013683E22C300BE528301BE5000053E3 0AFE14F010F4FFFFCAAE0000EB14001BE518101BE5 0AFE15001049FFFFEB0030A0E1FF3003E2000053E3 0AFE151010E6FFFF0A80009FE5060200EB10001BE5 0AFE15201014101BE518201BE5D00000EB10001BE5 0AFE15301014101BE518201BE50FFFFFEB0030A0E1 0AFE154010FF3003E2000053E30200000A4C009FE5 0AFE155010F80100EB010000EA44009FE5F50100EB 0AFE156010930000EB3C009FE5F20100EB0000A0E3 0AFE157010A4FEFFEB0030A0E30300A0E100A81BE9 0AFE158010A01DFE0AA41DFE0AE01DFE0A0C1EFE0A 0AFE159010381EFE0A641EFE0A181FFE0A281FFE0A 0AFE15A0103C1FFE0A481FFE0AB41EFE0A0DC0A0E1 0AFE15B01000D82DE904B04CE204D04DE210000BE5 0AFE15C01010301BE5013043E210300BE5010073E3 0AFE15D010FAFFFF1A00A81BE90DC0A0E100D82DE9 0AFE15E01004B04CE208D04DE210000BE510301BE5 0AFE15F01014300BE514301BE50300A0E100A81BE9 0AFE1600100DC0A0E100D82DE904B04CE204D04DE2 0AFE1610102228A0E3012A82E2042082E2E134A0E3 0AFE162010023883E2033C83E2003082E50333A0E3 0AFE163010053983E2003093E510300BE500A81BE9 0AFE1640100DC0A0E100D82DE904B04CE204D04DE2 0AFE1650102228A0E3012A82E2042082E29134A0E3 0AFE166010023883E2033C83E2003082E5C136A0E3 0AFE167010003093E510300BE52228A0E3012A82E2 0AFE168010042082E2E134A0E3023883E2033C83E2 0AFE169010003082E50333A0E3073983E20020A0E3 0AFE16A010002083E52228A0E3012A82E2042082E2 0AFE16B0108134A0E3023883E2033C83E2003082E5 0AFE16C0100333A0E3003093E510300BE5CBFFFFEB 0AFE16D01010301BE50300A0E100A81BE90DC0A0E1 0AFE16E01000D82DE904B04CE208D04DE2D3FFFFEB 0AFE16F0100030A0E110300BE510301BE5023503E2 0AFE170010000053E30500000A10301BE5073703E2 0AFE171010000053E30100000A10001BE5ADFFFFEB 0AFE17201010301BE5803003E2000053E30500000A 0AFE17301010301BE51C3003E2000053E30100000A 0AFE17401010001BE5A3FFFFEB10201BE50235A0E3 0AFE175010803083E2030052E10200001A0130A0E3 0AFE17601014300BE5010000EA0030A0E314300BE5 0AFE17701014001BE500A81BE90DC0A0E100D82DE9 0AFE17801004B04CE204D04DE22228A0E3012A82E2 0AFE179010042082E29134A0E3023883E2033C83E2 0AFE17A010003082E5C136A0E3003093E510300BE5 0AFE17B01000A81BE90DC0A0E100D82DE904B04CE2 0AFE17C010ECFFFFEB2228A0E3012A82E2042082E2 0AFE17D0108134A0E3023883E2033C83E2003082E5 0AFE17E01000A81BE90DC0A0E100D82DE904B04CE2 0AFE17F01004D04DE22228A0E3012A82E2042082E2 0AFE1800102238A0E3013A83E2043083E2003093E5 0AFE181010023183E3003082E52228A0E3012A82E2 0AFE1820102238A0E3013A83E2003093E5023183E3 0AFE183010003082E5FA0FA0E35BFFFFEB2228A0E3 0AFE184010012A82E2042082E2B134A0E3023883E2 0AFE185010033C83E2003082E50333A0E3233983E2 0AFE186010033B83E2003093E510300BE500A81BE9 0AFE1870100DC0A0E100D82DE904B04CE21CD04DE2 0AFE18801010000BE514100BE518200BE50030A0E3 0AFE1890101C300BE51C201BE518301BE5030052E1 0AFE18A0100000003A190000EAB2FFFFEB2228A0E3 0AFE18B010012A82E2042082E2F134A0E3023883E2 0AFE18C010033C83E2003082E514201BE51C301BE5 0AFE18D010031082E010201BE51C301BE5033082E0 0AFE18E010003093E5003081E57BFFFFEB0030A0E1 0AFE18F010FF3003E2000053E3FAFFFF0AACFFFFEB 0AFE1900101C301BE5043083E21C300BE5E0FFFFEA 0AFE19101000A81BE90DC0A0E100D82DE904B04CE2 0AFE1920100CD04DE210000BE52228A0E3012A82E2 0AFE193010042082E28134A0E3023883E2033C83E2 0AFE194010003082E510301BE5003093E514300BE5 0AFE1950102228A0E3012A82E2042082E29134A0E3 0AFE196010023883E2033C83E2003082E510301BE5 0AFE197010003093E518300BE52228A0E3012A82E2 0AFE198010042082E2E134A0E3023883E2033C83E2 0AFE199010003082E50229A0E310301BE5032082E0 0AFE19A0100030A0E3003082E52228A0E3012A82E2 0AFE19B010042082E28134A0E3023883E2033C83E2 0AFE19C010003082E510201BE50D3AA0E3D03083E2 0AFE19D010033883E1003082E53FFFFFEB0030A0E1 0AFE19E010FF3003E2000053E3FAFFFF0A70FFFFEB 0AFE19F01000A81BE90DC0A0E100D82DE904B04CE2 0AFE1A00105CFFFFEB2228A0E3012A82E2042082E2 0AFE1A1010E134A0E3023883E2033C83E2003082E5 0AFE1A20100333A0E3033983E20020A0E3002083E5 0AFE1A30102228A0E3012A82E2042082E28134A0E3 0AFE1A4010023883E2033C83E2003082E50323A0E3 0AFE1A5010032982E20339A0E3C03083E2033883E1 0AFE1A6010003082E500A81BE90DC0A0E100D82DE9 0AFE1A701004B04CE23FFFFFEB2228A0E3012A82E2 0AFE1A8010042082E2E134A0E3023883E2033C83E2 0AFE1A9010003082E50333A0E30A3983E20020A0E3 0AFE1AA010002083E52228A0E3012A82E2042082E2 0AFE1AB0108134A0E3023883E2033C83E2003082E5 0AFE1AC0100323A0E30A2982E20339A0E3C03083E2 0AFE1AD010033883E1003082E500A81BE90DC0A0E1 0AFE1AE01000D82DE904B04CE28729A0E3222E82E2 0AFE1AF0108739A0E3223E83E2003093E51E3CC3E3 0AFE1B0010003082E58729A0E38E2F82E28739A0E3 0AFE1B10108E3F83E2003093E51E3CC3E3003082E5 0AFE1B20108139A0E3823D83E20520A0E3002083E5 0AFE1B30108129A0E3822D82E2042082E20139A0E3 0AFE1B4010273083E2003082E58139A0E3823D83E2 0AFE1B50100C3083E20120A0E3002083E58129A0E3 0AFE1B6010822D82E2102082E22A3DA0E3013083E2 0AFE1B7010003082E58139A0E3823D83E2243083E2 0AFE1B80100F20A0E3002083E58139A0E3823D83E2 0AFE1B9010283083E28A20A0E3002083E58139A0E3 0AFE1BA010823D83E22C3083E20820A0E3002083E5 0AFE1BB01000A81BE90DC0A0E100D82DE904B04CE2 0AFE1BC0108139A0E3823D83E2183083E2003093E5 0AFE1BD010013003E2FF3003E20300A0E100A81BE9 0AFE1BE0100DC0A0E100D82DE904B04CE204D04DE2 0AFE1BF0100030A0E10D304BE58139A0E3823D83E2 0AFE1C0010183083E2003093E5013903E2000053E3 0AFE1C1010F8FFFF0A8139A0E3813D83E20D205BE5 0AFE1C2010002083E50D305BE50A0053E30A00001A 0AFE1C30108139A0E3823D83E2183083E2003093E5 0AFE1C4010013903E2000053E3F8FFFF0A8139A0E3 0AFE1C5010813D83E20D20A0E3002083E500A81BE9 0AFE1C60100DC0A0E100D82DE904B04CE20000A0E1 0AFE1C7010CFFFFFEB0030A0E1FF3003E2000053E3 0AFE1C8010FAFFFF0A8139A0E3023A83E2003093E5 0AFE1C9010FF3003E20300A0E100A81BE90DC0A0E1 0AFE1CA01000D82DE904B04CE204D04DE20030A0E1 0AFE1CB0100D304BE50D305BE52332A0E10E304BE5 0AFE1CC0100E305BE5090053E30300009A0E305BE5 0AFE1CD010373083E20E304BE5020000EA0E305BE5 0AFE1CE010303083E20E304BE50E305BE50300A0E1 0AFE1CF010BAFFFFEB0D305BE50F3003E20E304BE5 0AFE1D00100E305BE5090053E30300009A0E305BE5 0AFE1D1010373083E20E304BE5020000EA0E305BE5 0AFE1D2010303083E20E304BE50E305BE50300A0E1 0AFE1D3010AAFFFFEB00A81BE90DC0A0E100D82DE9 0AFE1D401004B04CE204D04DE210000BE510301BE5 0AFE1D50100030D3E5000053E30000001A080000EA 0AFE1D601010104BE2003091E50320A0E10020D2E5 0AFE1D7010013083E2003081E50200A0E197FFFFEB 0AFE1D8008F1FFFFEA00A81BE9 0AFE1DA4100A0D4D58314144532053796E632D666C 0AFE1DB4106173682050726F6772616D6D696E6720 0AFE1DC4105574696C6974792076302E3520323030 0AFE1DD410322F30382F32310A0D000000536F7572 0AFE1DE41063652061646472657373202873746F72 0AFE1DF410656420696E2030783041464530303030 0AFE1E0410293A2030780000005461726765742061 0AFE1E1410646472657373202873746F7265642069 0AFE1E24106E2030783041464530303034293A2030 0AFE1E34107800000053697A652020202020202020 0AFE1E44102020202873746F72656420696E203078 0AFE1E54103041464530303038293A203078000000 0AFE1E6410507265737320616E79206B657920746F 0AFE1E74102073746172742070726F6772616D6D69 0AFE1E84106E67202E2E2E00000A0D45726173696E 0AFE1E94106720666C617368202E2E2E000A0D5072 0AFE1EA4106F6772616D6D696E67202E2E2E000000 0AFE1EB4100A0D50726F6772616D6D696E67206669 0AFE1EC4106E69736865642E0A0D50726573732027 0AFE1ED410612720746F20636F6E74696E7565202E 0AFE1EE4102E2E2E000A0D566572696679696E6720 0AFE1EF410666C617368202E2E2E0000000A0D426C 0AFE1F0410616E6B20636865636B696E67202E2E2E 0AFE1F1410000000000A45726173696E67202E2E2E 0AFE1F2410000000000A50726F6772616D6D696E67 0AFE1F3410202E2E2E000000002073756363656564 0AFE1F44102E0A0000206661696C656420210A0000 0AFE100000 " } ######################################################### if [ "$#" -eq 2 ] ; then output_init > $2 output_uboot >> $2 output_flashprog >> $2 else output_init; output_uboot; output_flashprog; fi
1001-study-uboot
tools/img2brec.sh
Shell
gpl3
14,720
/* ** Easylogo TGA->header converter ** ============================== ** (C) 2000 by Paolo Scaffardi (arsenio@tin.it) ** AIRVENT SAM s.p.a - RIMINI(ITALY) ** (C) 2007-2008 Mike Frysinger <vapier@gentoo.org> ** ** This is still under construction! */ #include <errno.h> #include <getopt.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #pragma pack(1) /*#define ENABLE_ASCII_BANNERS */ typedef struct { unsigned char id; unsigned char ColorMapType; unsigned char ImageTypeCode; unsigned short ColorMapOrigin; unsigned short ColorMapLenght; unsigned char ColorMapEntrySize; unsigned short ImageXOrigin; unsigned short ImageYOrigin; unsigned short ImageWidth; unsigned short ImageHeight; unsigned char ImagePixelSize; unsigned char ImageDescriptorByte; } tga_header_t; typedef struct { unsigned char r, g, b; } rgb_t; typedef struct { unsigned char b, g, r; } bgr_t; typedef struct { unsigned char Cb, y1, Cr, y2; } yuyv_t; typedef struct { void *data, *palette; int width, height, pixels, bpp, pixel_size, size, palette_size, yuyv; } image_t; void *xmalloc (size_t size) { void *ret = malloc (size); if (!ret) { fprintf (stderr, "\nerror: malloc(%zu) failed: %s", size, strerror(errno)); exit (1); } return ret; } void StringUpperCase (char *str) { int count = strlen (str); char c; while (count--) { c = *str; if ((c >= 'a') && (c <= 'z')) *str = 'A' + (c - 'a'); str++; } } void StringLowerCase (char *str) { int count = strlen (str); char c; while (count--) { c = *str; if ((c >= 'A') && (c <= 'Z')) *str = 'a' + (c - 'A'); str++; } } void pixel_rgb_to_yuyv (rgb_t * rgb_pixel, yuyv_t * yuyv_pixel) { unsigned int pR, pG, pB; /* Transform (0-255) components to (0-100) */ pR = rgb_pixel->r * 100 / 255; pG = rgb_pixel->g * 100 / 255; pB = rgb_pixel->b * 100 / 255; /* Calculate YUV values (0-255) from RGB beetween 0-100 */ yuyv_pixel->y1 = yuyv_pixel->y2 = 209 * (pR + pG + pB) / 300 + 16; yuyv_pixel->Cb = pB - (pR / 4) - (pG * 3 / 4) + 128; yuyv_pixel->Cr = pR - (pG * 3 / 4) - (pB / 4) + 128; return; } void printlogo_rgb (rgb_t * data, int w, int h) { int x, y; for (y = 0; y < h; y++) { for (x = 0; x < w; x++, data++) if ((data->r < 30) /*&&(data->g == 0)&&(data->b == 0) */ ) printf (" "); else printf ("X"); printf ("\n"); } } void printlogo_yuyv (unsigned short *data, int w, int h) { int x, y; for (y = 0; y < h; y++) { for (x = 0; x < w; x++, data++) if (*data == 0x1080) /* Because of inverted on i386! */ printf (" "); else printf ("X"); printf ("\n"); } } static inline unsigned short le16_to_cpu (unsigned short val) { union { unsigned char pval[2]; unsigned short val; } swapped; swapped.val = val; return (swapped.pval[1] << 8) + swapped.pval[0]; } int image_load_tga (image_t * image, char *filename) { FILE *file; tga_header_t header; int i; unsigned char app; rgb_t *p; if ((file = fopen (filename, "rb")) == NULL) return -1; fread (&header, sizeof (header), 1, file); /* byte swap: tga is little endian, host is ??? */ header.ColorMapOrigin = le16_to_cpu (header.ColorMapOrigin); header.ColorMapLenght = le16_to_cpu (header.ColorMapLenght); header.ImageXOrigin = le16_to_cpu (header.ImageXOrigin); header.ImageYOrigin = le16_to_cpu (header.ImageYOrigin); header.ImageWidth = le16_to_cpu (header.ImageWidth); header.ImageHeight = le16_to_cpu (header.ImageHeight); image->width = header.ImageWidth; image->height = header.ImageHeight; switch (header.ImageTypeCode) { case 2: /* Uncompressed RGB */ image->yuyv = 0; image->palette_size = 0; image->palette = NULL; break; default: printf ("Format not supported!\n"); return -1; } image->bpp = header.ImagePixelSize; image->pixel_size = ((image->bpp - 1) / 8) + 1; image->pixels = image->width * image->height; image->size = image->pixels * image->pixel_size; image->data = xmalloc (image->size); if (image->bpp != 24) { printf ("Bpp not supported: %d!\n", image->bpp); return -1; } fread (image->data, image->size, 1, file); /* Swapping R and B values */ p = image->data; for (i = 0; i < image->pixels; i++, p++) { app = p->r; p->r = p->b; p->b = app; } /* Swapping image */ if (!(header.ImageDescriptorByte & 0x20)) { unsigned char *temp = xmalloc (image->size); int linesize = image->pixel_size * image->width; void *dest = image->data, *source = temp + image->size - linesize; printf ("S"); if (temp == NULL) { printf ("Cannot alloc temp buffer!\n"); return -1; } memcpy (temp, image->data, image->size); for (i = 0; i < image->height; i++, dest += linesize, source -= linesize) memcpy (dest, source, linesize); free (temp); } #ifdef ENABLE_ASCII_BANNERS printlogo_rgb (image->data, image->width, image->height); #endif fclose (file); return 0; } void image_free (image_t * image) { free (image->data); free (image->palette); } int image_rgb_to_yuyv (image_t * rgb_image, image_t * yuyv_image) { rgb_t *rgb_ptr = (rgb_t *) rgb_image->data; yuyv_t yuyv; unsigned short *dest; int count = 0; yuyv_image->pixel_size = 2; yuyv_image->bpp = 16; yuyv_image->yuyv = 1; yuyv_image->width = rgb_image->width; yuyv_image->height = rgb_image->height; yuyv_image->pixels = yuyv_image->width * yuyv_image->height; yuyv_image->size = yuyv_image->pixels * yuyv_image->pixel_size; dest = (unsigned short *) (yuyv_image->data = xmalloc (yuyv_image->size)); yuyv_image->palette = 0; yuyv_image->palette_size = 0; while ((count++) < rgb_image->pixels) { pixel_rgb_to_yuyv (rgb_ptr++, &yuyv); if ((count & 1) == 0) /* Was == 0 */ memcpy (dest, ((void *) &yuyv) + 2, sizeof (short)); else memcpy (dest, (void *) &yuyv, sizeof (short)); dest++; } #ifdef ENABLE_ASCII_BANNERS printlogo_yuyv (yuyv_image->data, yuyv_image->width, yuyv_image->height); #endif return 0; } int image_rgb888_to_rgb565(image_t *rgb888_image, image_t *rgb565_image) { rgb_t *rgb_ptr = (rgb_t *) rgb888_image->data; unsigned short *dest; int count = 0; rgb565_image->pixel_size = 2; rgb565_image->bpp = 16; rgb565_image->yuyv = 0; rgb565_image->width = rgb888_image->width; rgb565_image->height = rgb888_image->height; rgb565_image->pixels = rgb565_image->width * rgb565_image->height; rgb565_image->size = rgb565_image->pixels * rgb565_image->pixel_size; dest = (unsigned short *) (rgb565_image->data = xmalloc(rgb565_image->size)); rgb565_image->palette = 0; rgb565_image->palette_size = 0; while ((count++) < rgb888_image->pixels) { *dest++ = ((rgb_ptr->b & 0xF8) << 8) | ((rgb_ptr->g & 0xFC) << 3) | (rgb_ptr->r >> 3); rgb_ptr++; } return 0; } int use_gzip = 0; int image_save_header (image_t * image, char *filename, char *varname) { FILE *file = fopen (filename, "w"); char app[256], str[256] = "", def_name[64]; int count = image->size, col = 0; unsigned char *dataptr = image->data; if (file == NULL) return -1; /* Author information */ fprintf (file, "/*\n * Generated by EasyLogo, (C) 2000 by Paolo Scaffardi\n *\n"); fprintf (file, " * To use this, include it and call: easylogo_plot(screen,&%s, width,x,y)\n *\n", varname); fprintf (file, " * Where:\t'screen'\tis the pointer to the frame buffer\n"); fprintf (file, " *\t\t'width'\tis the screen width\n"); fprintf (file, " *\t\t'x'\t\tis the horizontal position\n"); fprintf (file, " *\t\t'y'\t\tis the vertical position\n */\n\n"); /* gzip compress */ if (use_gzip & 0x1) { const char *errstr = NULL; unsigned char *compressed; struct stat st; FILE *gz; char *gzfilename = xmalloc(strlen (filename) + 20); char *gzcmd = xmalloc(strlen (filename) + 20); sprintf (gzfilename, "%s.gz", filename); sprintf (gzcmd, "gzip > %s", gzfilename); gz = popen (gzcmd, "w"); if (!gz) { errstr = "\nerror: popen() failed"; goto done; } if (fwrite (image->data, image->size, 1, gz) != 1) { errstr = "\nerror: writing data to gzip failed"; goto done; } if (pclose (gz)) { errstr = "\nerror: gzip process failed"; goto done; } gz = fopen (gzfilename, "r"); if (!gz) { errstr = "\nerror: open() on gzip data failed"; goto done; } if (stat (gzfilename, &st)) { errstr = "\nerror: stat() on gzip file failed"; goto done; } compressed = xmalloc (st.st_size); if (fread (compressed, st.st_size, 1, gz) != 1) { errstr = "\nerror: reading gzip data failed"; goto done; } fclose (gz); unlink (gzfilename); dataptr = compressed; count = st.st_size; fprintf (file, "#define EASYLOGO_ENABLE_GZIP %i\n\n", count); if (use_gzip & 0x2) fprintf (file, "static unsigned char EASYLOGO_DECOMP_BUFFER[%i];\n\n", image->size); done: free (gzfilename); free (gzcmd); if (errstr) { perror (errstr); return -1; } } /* Headers */ fprintf (file, "#include <video_easylogo.h>\n\n"); /* Macros */ strcpy (def_name, varname); StringUpperCase (def_name); fprintf (file, "#define DEF_%s_WIDTH\t\t%d\n", def_name, image->width); fprintf (file, "#define DEF_%s_HEIGHT\t\t%d\n", def_name, image->height); fprintf (file, "#define DEF_%s_PIXELS\t\t%d\n", def_name, image->pixels); fprintf (file, "#define DEF_%s_BPP\t\t%d\n", def_name, image->bpp); fprintf (file, "#define DEF_%s_PIXEL_SIZE\t%d\n", def_name, image->pixel_size); fprintf (file, "#define DEF_%s_SIZE\t\t%d\n\n", def_name, image->size); /* Declaration */ fprintf (file, "unsigned char DEF_%s_DATA[] = {\n", def_name); /* Data */ while (count) switch (col) { case 0: sprintf (str, " 0x%02x", *dataptr++); col++; count--; break; case 16: fprintf (file, "%s", str); if (count > 0) fprintf (file, ","); fprintf (file, "\n"); col = 0; break; default: strcpy (app, str); sprintf (str, "%s, 0x%02x", app, *dataptr++); col++; count--; break; } if (col) fprintf (file, "%s\n", str); /* End of declaration */ fprintf (file, "};\n\n"); /* Variable */ fprintf (file, "fastimage_t %s = {\n", varname); fprintf (file, " DEF_%s_DATA,\n", def_name); fprintf (file, " DEF_%s_WIDTH,\n", def_name); fprintf (file, " DEF_%s_HEIGHT,\n", def_name); fprintf (file, " DEF_%s_BPP,\n", def_name); fprintf (file, " DEF_%s_PIXEL_SIZE,\n", def_name); fprintf (file, " DEF_%s_SIZE\n};\n", def_name); fclose (file); return 0; } #define DEF_FILELEN 256 static void usage (int exit_status) { puts ( "EasyLogo 1.0 (C) 2000 by Paolo Scaffardi\n" "\n" "Syntax: easylogo [options] inputfile [outputvar [outputfile]]\n" "\n" "Options:\n" " -r Output RGB888 instead of YUYV\n" " -s Output RGB565 instead of YUYV\n" " -g Compress with gzip\n" " -b Preallocate space in bss for decompressing image\n" " -h Help output\n" "\n" "Where: 'inputfile' is the TGA image to load\n" " 'outputvar' is the variable name to create\n" " 'outputfile' is the output header file (default is 'inputfile.h')" ); exit (exit_status); } int main (int argc, char *argv[]) { int c; bool use_rgb888 = false; bool use_rgb565 = false; char inputfile[DEF_FILELEN], outputfile[DEF_FILELEN], varname[DEF_FILELEN]; image_t rgb888_logo, rgb565_logo, yuyv_logo; while ((c = getopt(argc, argv, "hrsgb")) > 0) { switch (c) { case 'h': usage (0); break; case 'r': use_rgb888 = true; puts("Using 24-bit RGB888 Output Fromat"); break; case 's': use_rgb565 = true; puts("Using 16-bit RGB565 Output Fromat"); break; case 'g': use_gzip |= 0x1; puts ("Compressing with gzip"); break; case 'b': use_gzip |= 0x2; puts ("Preallocating bss space for decompressing image"); break; default: usage (1); break; } } c = argc - optind; if (c > 4 || c < 1) usage (1); strcpy (inputfile, argv[optind]); if (c > 1) strcpy (varname, argv[optind + 1]); else { /* transform "input.tga" to just "input" */ char *dot; strcpy (varname, inputfile); dot = strchr (varname, '.'); if (dot) *dot = '\0'; } if (c > 2) strcpy (outputfile, argv[optind + 2]); else { /* just append ".h" to input file name */ strcpy (outputfile, inputfile); strcat (outputfile, ".h"); } /* Make sure the output is sent as soon as we printf() */ setbuf(stdout, NULL); printf ("Doing '%s' (%s) from '%s'...", outputfile, varname, inputfile); /* Import TGA logo */ printf ("L"); if (image_load_tga(&rgb888_logo, inputfile) < 0) { printf ("input file not found!\n"); exit (1); } /* Convert, save, and free the image */ if (!use_rgb888 && !use_rgb565) { printf ("C"); image_rgb_to_yuyv(&rgb888_logo, &yuyv_logo); printf("S"); image_save_header(&yuyv_logo, outputfile, varname); image_free(&yuyv_logo); } else if (use_rgb565) { printf("C"); image_rgb888_to_rgb565(&rgb888_logo, &rgb565_logo); printf("S"); image_save_header(&rgb565_logo, outputfile, varname); image_free(&rgb565_logo); } else { printf("S"); image_save_header(&rgb888_logo, outputfile, varname); } /* Free original image and copy */ image_free(&rgb888_logo); printf ("\n"); return 0; }
1001-study-uboot
tools/easylogo/easylogo.c
C
gpl3
13,265
include $(TOPDIR)/config.mk all: $(obj)easylogo $(obj)easylogo: $(SRCTREE)/tools/easylogo/easylogo.c $(HOSTCC) $(HOSTCFLAGS_NOPED) $(HOSTLDFLAGS) -o $@ $^ clean: rm -f $(obj)easylogo .PHONY: all clean
1001-study-uboot
tools/easylogo/Makefile
Makefile
gpl3
207
#!/bin/sh make ./easylogo linux_logo.tga u_boot_logo video_logo.h mv video_logo.h ../../include
1001-study-uboot
tools/easylogo/runme.sh
Shell
gpl3
96
/* * (C) Copyright 2011 Free Electrons * David Wagner <david.wagner@free-electrons.com> * * Inspired from envcrc.c: * (C) Copyright 2001 * Paolo Scaffardi, AIRVENT SAM s.p.a - RIMINI(ITALY), arsenio@tin.it * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ /* We want the GNU version of basename() */ #define _GNU_SOURCE #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <unistd.h> #include <compiler.h> #include <sys/types.h> #include <sys/stat.h> #include <u-boot/crc.h> #define CRC_SIZE sizeof(uint32_t) static void usage(const char *exec_name) { fprintf(stderr, "%s [-h] [-r] [-b] [-p <byte>] " "-s <environment partition size> -o <output> <input file>\n" "\n" "This tool takes a key=value input file (same as would a " "`printenv' show) and generates the corresponding environment " "image, ready to be flashed.\n" "\n" "\tThe input file is in format:\n" "\t\tkey1=value1\n" "\t\tkey2=value2\n" "\t\t...\n" "\t-r : the environment has multiple copies in flash\n" "\t-b : the target is big endian (default is little endian)\n" "\t-p <byte> : fill the image with <byte> bytes instead of " "0xff bytes\n" "\n" "If the input file is \"-\", data is read from standard input\n", exec_name); } int main(int argc, char **argv) { uint32_t crc, targetendian_crc; const char *txt_filename = NULL, *bin_filename = NULL; int txt_fd, bin_fd; unsigned char *dataptr, *envptr; unsigned char *filebuf = NULL; unsigned int filesize = 0, envsize = 0, datasize = 0; int bigendian = 0; int redundant = 0; unsigned char padbyte = 0xff; int option; int ret = EXIT_SUCCESS; struct stat txt_file_stat; int fp, ep; const char *prg; prg = basename(argv[0]); /* Parse the cmdline */ while ((option = getopt(argc, argv, "s:o:rbp:h")) != -1) { switch (option) { case 's': datasize = strtol(optarg, NULL, 0); break; case 'o': bin_filename = strdup(optarg); if (!bin_filename) { fprintf(stderr, "Can't strdup() the output " "filename\n"); return EXIT_FAILURE; } break; case 'r': redundant = 1; break; case 'b': bigendian = 1; break; case 'p': padbyte = strtol(optarg, NULL, 0); break; case 'h': usage(prg); return EXIT_SUCCESS; default: fprintf(stderr, "Wrong option -%c\n", option); usage(prg); return EXIT_FAILURE; } } /* Check datasize and allocate the data */ if (datasize == 0) { fprintf(stderr, "Please specify the size of the envrionnment " "partition.\n"); usage(prg); return EXIT_FAILURE; } dataptr = malloc(datasize * sizeof(*dataptr)); if (!dataptr) { fprintf(stderr, "Can't alloc dataptr.\n"); return EXIT_FAILURE; } /* * envptr points to the beginning of the actual environment (after the * crc and possible `redundant' bit */ envsize = datasize - (CRC_SIZE + redundant); envptr = dataptr + CRC_SIZE + redundant; /* Pad the environment with the padding byte */ memset(envptr, padbyte, envsize); /* Open the input file ... */ if (optind >= argc) { fprintf(stderr, "Please specify an input filename\n"); return EXIT_FAILURE; } txt_filename = argv[optind]; if (strcmp(txt_filename, "-") == 0) { int readbytes = 0; int readlen = sizeof(*envptr) * 2048; txt_fd = STDIN_FILENO; do { filebuf = realloc(filebuf, readlen); readbytes = read(txt_fd, filebuf + filesize, readlen); filesize += readbytes; } while (readbytes == readlen); } else { txt_fd = open(txt_filename, O_RDONLY); if (txt_fd == -1) { fprintf(stderr, "Can't open \"%s\": %s\n", txt_filename, strerror(errno)); return EXIT_FAILURE; } /* ... and check it */ ret = fstat(txt_fd, &txt_file_stat); if (ret == -1) { fprintf(stderr, "Can't stat() on \"%s\": " "%s\n", txt_filename, strerror(errno)); return EXIT_FAILURE; } filesize = txt_file_stat.st_size; /* Read the raw input file and transform it */ filebuf = malloc(sizeof(*envptr) * filesize); ret = read(txt_fd, filebuf, sizeof(*envptr) * filesize); if (ret != sizeof(*envptr) * filesize) { fprintf(stderr, "Can't read the whole input file\n"); return EXIT_FAILURE; } ret = close(txt_fd); } /* * The right test to do is "=>" (not ">") because of the additionnal * ending \0. See below. */ if (filesize >= envsize) { fprintf(stderr, "The input file is larger than the " "envrionnment partition size\n"); return EXIT_FAILURE; } /* Replace newlines separating variables with \0 */ for (fp = 0, ep = 0 ; fp < filesize ; fp++) { if (filebuf[fp] == '\n') { if (fp == 0) { /* * Newline at the beggining of the file ? * Ignore it. */ continue; } else if (filebuf[fp-1] == '\\') { /* * Embedded newline in a variable. * * The backslash was added to the envptr ; * rewind and replace it with a newline */ ep--; envptr[ep++] = '\n'; } else { /* End of a variable */ envptr[ep++] = '\0'; } } else if (filebuf[fp] == '#') { if (fp != 0 && filebuf[fp-1] == '\n') { /* This line is a comment, let's skip it */ while (fp < txt_file_stat.st_size && fp++ && filebuf[fp] != '\n'); } else { envptr[ep++] = filebuf[fp]; } } else { envptr[ep++] = filebuf[fp]; } } /* * Make sure there is a final '\0' * And do it again on the next byte to mark the end of the environment. */ if (envptr[ep-1] != '\0') { envptr[ep++] = '\0'; /* * The text file doesn't have an ending newline. We need to * check the env size again to make sure we have room for two \0 */ if (ep >= envsize) { fprintf(stderr, "The environment file is too large for " "the target environment storage\n"); return EXIT_FAILURE; } envptr[ep] = '\0'; } else { envptr[ep] = '\0'; } /* Computes the CRC and put it at the beginning of the data */ crc = crc32(0, envptr, envsize); targetendian_crc = bigendian ? cpu_to_be32(crc) : cpu_to_le32(crc); memcpy(dataptr, &targetendian_crc, sizeof(uint32_t)); bin_fd = creat(bin_filename, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); if (bin_fd == -1) { fprintf(stderr, "Can't open output file \"%s\": %s\n", bin_filename, strerror(errno)); return EXIT_FAILURE; } if (write(bin_fd, dataptr, sizeof(*dataptr) * datasize) != sizeof(*dataptr) * datasize) { fprintf(stderr, "write() failed: %s\n", strerror(errno)); return EXIT_FAILURE; } ret = close(bin_fd); return ret; }
1001-study-uboot
tools/mkenvimage.c
C
gpl3
7,340