1*27b03b36SApple OSS Distributions#!/usr/bin/env python 2*27b03b36SApple OSS Distributions# machtrace_parse.py 3*27b03b36SApple OSS Distributions# Parse Mach IPC kmsg data trace from XNU 4*27b03b36SApple OSS Distributions# 5*27b03b36SApple OSS Distributions# Jeremy C. Andrus <[email protected]> 6*27b03b36SApple OSS Distributions# 7*27b03b36SApple OSS Distributionsfrom __future__ import division 8*27b03b36SApple OSS Distributions 9*27b03b36SApple OSS Distributionsimport argparse 10*27b03b36SApple OSS Distributionsimport subprocess 11*27b03b36SApple OSS Distributionsimport sys 12*27b03b36SApple OSS Distributionsimport re 13*27b03b36SApple OSS Distributionsfrom collections import deque 14*27b03b36SApple OSS Distributions 15*27b03b36SApple OSS Distributionsimport os.path 16*27b03b36SApple OSS Distributions 17*27b03b36SApple OSS Distributionsfrom collections import defaultdict 18*27b03b36SApple OSS Distributions 19*27b03b36SApple OSS Distributionsg_verbose = 0 20*27b03b36SApple OSS Distributionsg_min_messages = 10 21*27b03b36SApple OSS Distributionsg_rolling_window = 200 22*27b03b36SApple OSS Distributions 23*27b03b36SApple OSS Distributionsdef RunCommand(cmd_string): 24*27b03b36SApple OSS Distributions """ 25*27b03b36SApple OSS Distributions returns: (int,str) : exit_code and output_str 26*27b03b36SApple OSS Distributions """ 27*27b03b36SApple OSS Distributions global g_verbose 28*27b03b36SApple OSS Distributions if g_verbose > 1: 29*27b03b36SApple OSS Distributions sys.stderr.write("\tCMD:{}\n".format(cmd_string)) 30*27b03b36SApple OSS Distributions output_str = "" 31*27b03b36SApple OSS Distributions exit_code = 0 32*27b03b36SApple OSS Distributions try: 33*27b03b36SApple OSS Distributions output_str = subprocess.check_output(cmd_string, shell=True) 34*27b03b36SApple OSS Distributions except subprocess.CalledProcessError, e: 35*27b03b36SApple OSS Distributions exit_code = e.returncode 36*27b03b36SApple OSS Distributions finally: 37*27b03b36SApple OSS Distributions return (exit_code, output_str.strip()) 38*27b03b36SApple OSS Distributions 39*27b03b36SApple OSS Distributions 40*27b03b36SApple OSS Distributionsclass IPCNode: 41*27b03b36SApple OSS Distributions """ Class interface to a graph node representing a logical service name. 42*27b03b36SApple OSS Distributions In general, this should correspond to a unique binary on the system 43*27b03b36SApple OSS Distributions which could be started / stopped as different PIDs throughout the life 44*27b03b36SApple OSS Distributions of the system. 45*27b03b36SApple OSS Distributions """ 46*27b03b36SApple OSS Distributions def __init__(self, name = ''): 47*27b03b36SApple OSS Distributions global g_verbose 48*27b03b36SApple OSS Distributions self.nname = "L_" + name.replace(".", "_").replace("-", "_") 49*27b03b36SApple OSS Distributions self.nicename = name 50*27b03b36SApple OSS Distributions self.outgoing = {} 51*27b03b36SApple OSS Distributions self.incoming = {} 52*27b03b36SApple OSS Distributions self.msg_stat = {'o.num':0, 'o.first':0.0, 'o.last':0.0, 'o.window':deque(), 'o.avg':0, 'o.peak':0, \ 53*27b03b36SApple OSS Distributions 'i.num':0, 'i.first':0.0, 'i.last':0.0, 'i.window':deque(), 'i.avg':0, 'i.peak':0} 54*27b03b36SApple OSS Distributions self.pidset = {} 55*27b03b36SApple OSS Distributions self.scalefactor = 100.0 56*27b03b36SApple OSS Distributions if g_verbose > 0: 57*27b03b36SApple OSS Distributions sys.stderr.write(' New node: "{}"{}\n'.format(self.nname, ' '*50)) 58*27b03b36SApple OSS Distributions 59*27b03b36SApple OSS Distributions def add_outgoing_edge(self, edge, time): 60*27b03b36SApple OSS Distributions self.outgoing[edge.ename()] = [edge, time] 61*27b03b36SApple OSS Distributions 62*27b03b36SApple OSS Distributions def add_incoming_edge(self, edge, time): 63*27b03b36SApple OSS Distributions self.incoming[edge.ename()] = [edge, time] 64*27b03b36SApple OSS Distributions 65*27b03b36SApple OSS Distributions def addpid(self, pid, time): 66*27b03b36SApple OSS Distributions if not pid in self.pidset: 67*27b03b36SApple OSS Distributions self.pidset[pid] = [time, 0] 68*27b03b36SApple OSS Distributions self.pidset[pid][1] = time 69*27b03b36SApple OSS Distributions 70*27b03b36SApple OSS Distributions def incoming_msg(self, size, time_us): 71*27b03b36SApple OSS Distributions global g_min_messages 72*27b03b36SApple OSS Distributions global g_rolling_window 73*27b03b36SApple OSS Distributions num = self.msg_stat['i.num'] + 1 74*27b03b36SApple OSS Distributions self.msg_stat['i.num'] = num 75*27b03b36SApple OSS Distributions time_us = float(time_us) 76*27b03b36SApple OSS Distributions if self.msg_stat['i.first'] == 0.0: 77*27b03b36SApple OSS Distributions self.msg_stat['i.first'] = time_us 78*27b03b36SApple OSS Distributions self.msg_stat['i.last'] = time_us 79*27b03b36SApple OSS Distributions else: 80*27b03b36SApple OSS Distributions self.msg_stat['i.last'] = time_us 81*27b03b36SApple OSS Distributions if num > g_min_messages: 82*27b03b36SApple OSS Distributions avg = (num * self.scalefactor) / (time_us - self.msg_stat['i.first']) 83*27b03b36SApple OSS Distributions self.msg_stat['i.avg'] = avg 84*27b03b36SApple OSS Distributions 85*27b03b36SApple OSS Distributions self.msg_stat['i.window'].append(time_us) 86*27b03b36SApple OSS Distributions if len(self.msg_stat['i.window']) > g_rolling_window: 87*27b03b36SApple OSS Distributions self.msg_stat['i.window'].popleft() 88*27b03b36SApple OSS Distributions n = len(self.msg_stat['i.window']) 89*27b03b36SApple OSS Distributions ravg = float(len(self.msg_stat['i.window']) * self.scalefactor) / \ 90*27b03b36SApple OSS Distributions (self.msg_stat['i.window'][-1] - self.msg_stat['i.window'][0]) 91*27b03b36SApple OSS Distributions if ravg > self.msg_stat['i.peak']: 92*27b03b36SApple OSS Distributions self.msg_stat['i.peak'] = ravg 93*27b03b36SApple OSS Distributions 94*27b03b36SApple OSS Distributions def outgoing_msg(self, size, time_us): 95*27b03b36SApple OSS Distributions global g_min_messages 96*27b03b36SApple OSS Distributions global g_rolling_window 97*27b03b36SApple OSS Distributions num = self.msg_stat['o.num'] + 1 98*27b03b36SApple OSS Distributions self.msg_stat['o.num'] = num 99*27b03b36SApple OSS Distributions time_us = float(time_us) 100*27b03b36SApple OSS Distributions if self.msg_stat['o.first'] == 0.0: 101*27b03b36SApple OSS Distributions self.msg_stat['o.first'] = time_us 102*27b03b36SApple OSS Distributions self.msg_stat['o.last'] = time_us 103*27b03b36SApple OSS Distributions else: 104*27b03b36SApple OSS Distributions self.msg_stat['o.last'] = time_us 105*27b03b36SApple OSS Distributions if num > g_min_messages: 106*27b03b36SApple OSS Distributions avg = (num * self.scalefactor) / (time_us - self.msg_stat['o.first']) 107*27b03b36SApple OSS Distributions self.msg_stat['o.avg'] = avg 108*27b03b36SApple OSS Distributions 109*27b03b36SApple OSS Distributions self.msg_stat['o.window'].append(time_us) 110*27b03b36SApple OSS Distributions if len(self.msg_stat['o.window']) > g_rolling_window: 111*27b03b36SApple OSS Distributions self.msg_stat['o.window'].popleft() 112*27b03b36SApple OSS Distributions n = len(self.msg_stat['o.window']) 113*27b03b36SApple OSS Distributions ravg = float(len(self.msg_stat['o.window']) * self.scalefactor) / \ 114*27b03b36SApple OSS Distributions (self.msg_stat['o.window'][-1] - self.msg_stat['o.window'][0]) 115*27b03b36SApple OSS Distributions if ravg > self.msg_stat['o.peak']: 116*27b03b36SApple OSS Distributions self.msg_stat['o.peak'] = ravg 117*27b03b36SApple OSS Distributions 118*27b03b36SApple OSS Distributions def nmsgs(self): 119*27b03b36SApple OSS Distributions return self.msg_stat['o.num'], self.msg_stat['i.num'] 120*27b03b36SApple OSS Distributions 121*27b03b36SApple OSS Distributions def recycled(self): 122*27b03b36SApple OSS Distributions return len(self.pidset) 123*27b03b36SApple OSS Distributions 124*27b03b36SApple OSS Distributions def label(self, timebase = 1000000.0): 125*27b03b36SApple OSS Distributions oavg = float(self.msg_stat['o.avg']) / self.scalefactor 126*27b03b36SApple OSS Distributions opeak = float(self.msg_stat['o.peak']) / self.scalefactor 127*27b03b36SApple OSS Distributions oactive = self.msg_stat['o.last'] - self.msg_stat['o.first'] 128*27b03b36SApple OSS Distributions iavg = float(self.msg_stat['i.avg']) / self.scalefactor 129*27b03b36SApple OSS Distributions ipeak = float(self.msg_stat['i.peak']) / self.scalefactor 130*27b03b36SApple OSS Distributions iactive = self.msg_stat['i.last'] - self.msg_stat['i.first'] 131*27b03b36SApple OSS Distributions if timebase > 0.0: 132*27b03b36SApple OSS Distributions oavg = oavg * timebase 133*27b03b36SApple OSS Distributions opeak = opeak * timebase 134*27b03b36SApple OSS Distributions oactive = oactive / timebase 135*27b03b36SApple OSS Distributions iavg = iavg * timebase 136*27b03b36SApple OSS Distributions ipeak = ipeak * timebase 137*27b03b36SApple OSS Distributions iactive = iactive / timebase 138*27b03b36SApple OSS Distributions return "{:s}\\no:{:d}/({:d}:{:.1f}s)/{:.1f}:{:.1f})\\ni:{:d}({:d}:{:.1f}s)/{:.1f}:{:.1f})\\nR:{:d}"\ 139*27b03b36SApple OSS Distributions .format(self.nicename, \ 140*27b03b36SApple OSS Distributions len(self.outgoing), self.msg_stat['o.num'], oactive, oavg, opeak, \ 141*27b03b36SApple OSS Distributions len(self.incoming), self.msg_stat['i.num'], iactive, iavg, ipeak, \ 142*27b03b36SApple OSS Distributions len(self.pidset)) 143*27b03b36SApple OSS Distributions 144*27b03b36SApple OSS Distributionsclass IPCEdge: 145*27b03b36SApple OSS Distributions """ Class interface to an graph edge representing two services / programs 146*27b03b36SApple OSS Distributions communicating via Mach IPC. Note that this communication could 147*27b03b36SApple OSS Distributions use many different PIDs. The connected graph nodes (see IPCNode) 148*27b03b36SApple OSS Distributions represent logical services on the system which could be instantiated 149*27b03b36SApple OSS Distributions as many different PIDs depending on the lifecycle of the process 150*27b03b36SApple OSS Distributions (dictated in part by launchd). 151*27b03b36SApple OSS Distributions """ 152*27b03b36SApple OSS Distributions 153*27b03b36SApple OSS Distributions F_TRACED = 0x00000100 154*27b03b36SApple OSS Distributions F_COMPLEX = 0x00000200 155*27b03b36SApple OSS Distributions F_OOLMEM = 0x00000400 156*27b03b36SApple OSS Distributions F_VCPY = 0x00000800 157*27b03b36SApple OSS Distributions F_PCPY = 0x00001000 158*27b03b36SApple OSS Distributions F_SND64 = 0x00002000 159*27b03b36SApple OSS Distributions F_RAISEIMP = 0x00004000 160*27b03b36SApple OSS Distributions F_APP_SRC = 0x00008000 161*27b03b36SApple OSS Distributions F_APP_DST = 0x00010000 162*27b03b36SApple OSS Distributions F_DAEMON_SRC = 0x00020000 163*27b03b36SApple OSS Distributions F_DAEMON_DST = 0x00040000 164*27b03b36SApple OSS Distributions F_DST_NDFLTQ = 0x00080000 165*27b03b36SApple OSS Distributions F_SRC_NDFLTQ = 0x00100000 166*27b03b36SApple OSS Distributions F_DST_SONCE = 0x00200000 167*27b03b36SApple OSS Distributions F_SRC_SONCE = 0x00400000 168*27b03b36SApple OSS Distributions F_CHECKIN = 0x00800000 169*27b03b36SApple OSS Distributions F_ONEWAY = 0x01000000 170*27b03b36SApple OSS Distributions F_IOKIT = 0x02000000 171*27b03b36SApple OSS Distributions F_SNDRCV = 0x04000000 172*27b03b36SApple OSS Distributions F_DSTQFULL = 0x08000000 173*27b03b36SApple OSS Distributions F_VOUCHER = 0x10000000 174*27b03b36SApple OSS Distributions F_TIMER = 0x20000000 175*27b03b36SApple OSS Distributions F_SEMA = 0x40000000 176*27b03b36SApple OSS Distributions F_PORTS_MASK = 0x000000FF 177*27b03b36SApple OSS Distributions 178*27b03b36SApple OSS Distributions DTYPES = [ 'std', 'xpc', 'iokit', 'std.reply', 'xpc.reply', 'iokit.reply' ] 179*27b03b36SApple OSS Distributions DFLAVORS = [ 'std', 'ool', 'vcpy', 'iokit' ] 180*27b03b36SApple OSS Distributions 181*27b03b36SApple OSS Distributions def __init__(self, src = IPCNode(), dst = IPCNode(), data = '0', flags = '0', time = 0.0): 182*27b03b36SApple OSS Distributions self.src = src 183*27b03b36SApple OSS Distributions self.dst = dst 184*27b03b36SApple OSS Distributions self.flags = 0 185*27b03b36SApple OSS Distributions self.dweight = 0 186*27b03b36SApple OSS Distributions self.pweight = 0 187*27b03b36SApple OSS Distributions self.weight = 0 188*27b03b36SApple OSS Distributions self._data = { 'std':0, 'ool':0, 'vcpy':0, 'iokit':0 } 189*27b03b36SApple OSS Distributions self._dtype = { 'std':0, 'xpc':0, 'iokit':0, 'std.reply':0, 'xpc.reply':0, 'iokit.reply':0 } 190*27b03b36SApple OSS Distributions self._msgs = { 'std':0, 'ool':0, 'vcpy':0, 'iokit':0 } 191*27b03b36SApple OSS Distributions self._mtype = { 'std':0, 'xpc':0, 'iokit':0, 'std.reply':0, 'xpc.reply':0, 'iokit.reply':0 } 192*27b03b36SApple OSS Distributions self.ports = 0 193*27b03b36SApple OSS Distributions self.task64 = False 194*27b03b36SApple OSS Distributions self.task32 = False 195*27b03b36SApple OSS Distributions self.src.add_outgoing_edge(self, time) 196*27b03b36SApple OSS Distributions self.dst.add_incoming_edge(self, time) 197*27b03b36SApple OSS Distributions self.addmsg(data, flags, time) 198*27b03b36SApple OSS Distributions 199*27b03b36SApple OSS Distributions def ename(self): 200*27b03b36SApple OSS Distributions return self.src.nname + " -> " + self.dst.nname 201*27b03b36SApple OSS Distributions 202*27b03b36SApple OSS Distributions def msgdata(self): 203*27b03b36SApple OSS Distributions return self._data, self._dtype 204*27b03b36SApple OSS Distributions 205*27b03b36SApple OSS Distributions def data(self, flavor = None): 206*27b03b36SApple OSS Distributions if not flavor: 207*27b03b36SApple OSS Distributions return sum(self._data.itervalues()) 208*27b03b36SApple OSS Distributions elif flavor in self._data: 209*27b03b36SApple OSS Distributions return self._data[flavor] 210*27b03b36SApple OSS Distributions else: 211*27b03b36SApple OSS Distributions return 0 212*27b03b36SApple OSS Distributions 213*27b03b36SApple OSS Distributions def dtype(self, type): 214*27b03b36SApple OSS Distributions if not type: 215*27b03b36SApple OSS Distributions return sum(self._dtype.itervalues()) 216*27b03b36SApple OSS Distributions elif type in self._dtype: 217*27b03b36SApple OSS Distributions return self._dtype[type] 218*27b03b36SApple OSS Distributions else: 219*27b03b36SApple OSS Distributions return 0 220*27b03b36SApple OSS Distributions 221*27b03b36SApple OSS Distributions def msgs(self, flavor = None): 222*27b03b36SApple OSS Distributions if not flavor: 223*27b03b36SApple OSS Distributions return sum(self._msgs.itervalues()) 224*27b03b36SApple OSS Distributions elif flavor in self._msgs: 225*27b03b36SApple OSS Distributions return self._msgs[flavor] 226*27b03b36SApple OSS Distributions else: 227*27b03b36SApple OSS Distributions return 0 228*27b03b36SApple OSS Distributions 229*27b03b36SApple OSS Distributions def mtype(self, type): 230*27b03b36SApple OSS Distributions if not type: 231*27b03b36SApple OSS Distributions return sum(self._mtype.itervalues()) 232*27b03b36SApple OSS Distributions elif type in self._mtype: 233*27b03b36SApple OSS Distributions return self._mtype[type] 234*27b03b36SApple OSS Distributions else: 235*27b03b36SApple OSS Distributions return 0 236*27b03b36SApple OSS Distributions 237*27b03b36SApple OSS Distributions def selfedge(self): 238*27b03b36SApple OSS Distributions if self.src.nname == self.dst.nname: 239*27b03b36SApple OSS Distributions return True 240*27b03b36SApple OSS Distributions return False 241*27b03b36SApple OSS Distributions 242*27b03b36SApple OSS Distributions def addmsg(self, data_hex_str, flags_str, time): 243*27b03b36SApple OSS Distributions global g_verbose 244*27b03b36SApple OSS Distributions f = int(flags_str, 16) 245*27b03b36SApple OSS Distributions self.flags |= f 246*27b03b36SApple OSS Distributions df = {f:0 for f in self.DFLAVORS} 247*27b03b36SApple OSS Distributions dt = {t:0 for t in self.DTYPES} 248*27b03b36SApple OSS Distributions if not f & self.F_TRACED: 249*27b03b36SApple OSS Distributions return df, dt 250*27b03b36SApple OSS Distributions self.weight += 1 251*27b03b36SApple OSS Distributions if f & self.F_SND64: 252*27b03b36SApple OSS Distributions self.task64 = True 253*27b03b36SApple OSS Distributions else: 254*27b03b36SApple OSS Distributions self.task32 = True 255*27b03b36SApple OSS Distributions if not f & self.F_COMPLEX: 256*27b03b36SApple OSS Distributions self.dweight += 1 257*27b03b36SApple OSS Distributions df['std'] = int(data_hex_str, 16) 258*27b03b36SApple OSS Distributions if f & self.F_IOKIT: 259*27b03b36SApple OSS Distributions df['iokit'] = df['std'] 260*27b03b36SApple OSS Distributions df['std'] = 0 261*27b03b36SApple OSS Distributions self._data['iokit'] += df['iokit'] 262*27b03b36SApple OSS Distributions self._msgs['iokit'] += 1 263*27b03b36SApple OSS Distributions else: 264*27b03b36SApple OSS Distributions self._data['std'] += df['std'] 265*27b03b36SApple OSS Distributions self._msgs['std'] += 1 266*27b03b36SApple OSS Distributions elif f & self.F_OOLMEM: 267*27b03b36SApple OSS Distributions self.dweight += 1 268*27b03b36SApple OSS Distributions df['ool'] = int(data_hex_str, 16) 269*27b03b36SApple OSS Distributions if f & self.F_IOKIT: 270*27b03b36SApple OSS Distributions df['iokit'] = df['ool'] 271*27b03b36SApple OSS Distributions df['ool'] = 0 272*27b03b36SApple OSS Distributions self._data['iokit'] += df['iokit'] 273*27b03b36SApple OSS Distributions self._msgs['iokit'] += 1 274*27b03b36SApple OSS Distributions elif f & self.F_VCPY: 275*27b03b36SApple OSS Distributions df['vcpy'] = df['ool'] 276*27b03b36SApple OSS Distributions df['ool'] = 0 277*27b03b36SApple OSS Distributions self._data['vcpy'] += df['vcpy'] 278*27b03b36SApple OSS Distributions self._msgs['vcpy'] += 1 279*27b03b36SApple OSS Distributions else: 280*27b03b36SApple OSS Distributions self._data['ool'] += df['ool'] 281*27b03b36SApple OSS Distributions self._msgs['ool'] += 1 282*27b03b36SApple OSS Distributions # Complex messages can contain ports and data 283*27b03b36SApple OSS Distributions if f & self.F_COMPLEX: 284*27b03b36SApple OSS Distributions nports = f & self.F_PORTS_MASK 285*27b03b36SApple OSS Distributions if nports > 0: 286*27b03b36SApple OSS Distributions self.pweight += 1 287*27b03b36SApple OSS Distributions self.ports += nports 288*27b03b36SApple OSS Distributions dsize = sum(df.values()) 289*27b03b36SApple OSS Distributions if f & self.F_DST_SONCE: 290*27b03b36SApple OSS Distributions if f & self.F_IOKIT: 291*27b03b36SApple OSS Distributions dt['iokit.reply'] = dsize 292*27b03b36SApple OSS Distributions self._dtype['iokit.reply'] += dsize 293*27b03b36SApple OSS Distributions self._mtype['iokit.reply'] += 1 294*27b03b36SApple OSS Distributions elif f & (self.F_DST_NDFLTQ | self.F_SRC_NDFLTQ): 295*27b03b36SApple OSS Distributions dt['xpc.reply'] = dsize 296*27b03b36SApple OSS Distributions self._dtype['xpc.reply'] += dsize 297*27b03b36SApple OSS Distributions self._mtype['xpc.reply'] += 1 298*27b03b36SApple OSS Distributions else: 299*27b03b36SApple OSS Distributions dt['std.reply'] = dsize 300*27b03b36SApple OSS Distributions self._dtype['std.reply'] += dsize 301*27b03b36SApple OSS Distributions self._mtype['std.reply'] += 1 302*27b03b36SApple OSS Distributions elif f & self.F_IOKIT: 303*27b03b36SApple OSS Distributions dt['iokit'] = dsize 304*27b03b36SApple OSS Distributions self._dtype['iokit'] += dsize 305*27b03b36SApple OSS Distributions self._mtype['iokit'] += 1 306*27b03b36SApple OSS Distributions elif f & (self.F_DST_NDFLTQ | self.F_SRC_NDFLTQ): 307*27b03b36SApple OSS Distributions dt['xpc'] = dsize 308*27b03b36SApple OSS Distributions self._dtype['xpc'] += dsize 309*27b03b36SApple OSS Distributions self._mtype['xpc'] += 1 310*27b03b36SApple OSS Distributions else: 311*27b03b36SApple OSS Distributions dt['std'] = dsize 312*27b03b36SApple OSS Distributions self._dtype['std'] += dsize 313*27b03b36SApple OSS Distributions self._mtype['std'] += 1 314*27b03b36SApple OSS Distributions self.src.outgoing_msg(dsize, time) 315*27b03b36SApple OSS Distributions self.dst.incoming_msg(dsize, time) 316*27b03b36SApple OSS Distributions if g_verbose > 2: 317*27b03b36SApple OSS Distributions sys.stderr.write(' {}->{} ({}/{}){}\r'.format(self.src.nname, self.dst.nname, df['ool'], df['std'], ' ' *50)) 318*27b03b36SApple OSS Distributions return df, dt 319*27b03b36SApple OSS Distributions 320*27b03b36SApple OSS Distributions def avgmsg(self): 321*27b03b36SApple OSS Distributions avgsz = self.data() / self.dweight 322*27b03b36SApple OSS Distributions msgs_with_data = self.dweight / self.weight 323*27b03b36SApple OSS Distributions avgports = self.ports / self.pweight 324*27b03b36SApple OSS Distributions msgs_with_ports = self.pweight / self.weight 325*27b03b36SApple OSS Distributions return (avgsz, msgs_with_data, avgports, msgs_with_ports) 326*27b03b36SApple OSS Distributions 327*27b03b36SApple OSS Distributions 328*27b03b36SApple OSS Distributionsclass EdgeError(Exception): 329*27b03b36SApple OSS Distributions """ IPCEdge exception class 330*27b03b36SApple OSS Distributions """ 331*27b03b36SApple OSS Distributions def __init__(self, edge, nm): 332*27b03b36SApple OSS Distributions self.msg = "Edge {} (w:{}) didn't match incoming name {}!".format(edge.ename(), edge.weight, nm) 333*27b03b36SApple OSS Distributions 334*27b03b36SApple OSS Distributionsclass IPCGraph: 335*27b03b36SApple OSS Distributions """ Class interface to a directed graph of IPC interconnectivity 336*27b03b36SApple OSS Distributions """ 337*27b03b36SApple OSS Distributions def __init__(self, name = '', timebase = 0.0): 338*27b03b36SApple OSS Distributions global g_verbose 339*27b03b36SApple OSS Distributions if len(name) == 0: 340*27b03b36SApple OSS Distributions self.name = 'ipcgraph' 341*27b03b36SApple OSS Distributions else: 342*27b03b36SApple OSS Distributions self.name = name 343*27b03b36SApple OSS Distributions if g_verbose > 0: 344*27b03b36SApple OSS Distributions sys.stderr.write('Creating new IPCGraph named {}...\n'.format(self.name)) 345*27b03b36SApple OSS Distributions self.nodes = {} 346*27b03b36SApple OSS Distributions self.edges = {} 347*27b03b36SApple OSS Distributions self.msgs = defaultdict(lambda: {f:0 for f in IPCEdge.DFLAVORS}) 348*27b03b36SApple OSS Distributions self.msgtypes = defaultdict(lambda: {t:0 for t in IPCEdge.DTYPES}) 349*27b03b36SApple OSS Distributions self.nmsgs = 0 350*27b03b36SApple OSS Distributions self.totals = {} 351*27b03b36SApple OSS Distributions self.maxdweight = 0 352*27b03b36SApple OSS Distributions for f in IPCEdge.DFLAVORS: 353*27b03b36SApple OSS Distributions self.totals['n'+f] = 0 354*27b03b36SApple OSS Distributions self.totals['D'+f] = 0 355*27b03b36SApple OSS Distributions if timebase and timebase > 0.0: 356*27b03b36SApple OSS Distributions self.timebase = timebase 357*27b03b36SApple OSS Distributions else: 358*27b03b36SApple OSS Distributions self.timebase = 0.0 359*27b03b36SApple OSS Distributions 360*27b03b36SApple OSS Distributions def __iter__(self): 361*27b03b36SApple OSS Distributions return edges 362*27b03b36SApple OSS Distributions 363*27b03b36SApple OSS Distributions def edgename(self, src, dst): 364*27b03b36SApple OSS Distributions if src and dst: 365*27b03b36SApple OSS Distributions return src.nname + ' -> ' + dst.nname 366*27b03b36SApple OSS Distributions return '' 367*27b03b36SApple OSS Distributions 368*27b03b36SApple OSS Distributions def addmsg(self, src_str, src_pid, dst_str, dst_pid, data_hex_str, flags_str, time): 369*27b03b36SApple OSS Distributions src = None 370*27b03b36SApple OSS Distributions dst = None 371*27b03b36SApple OSS Distributions for k, v in self.nodes.iteritems(): 372*27b03b36SApple OSS Distributions if not src and k == src_str: 373*27b03b36SApple OSS Distributions src = v 374*27b03b36SApple OSS Distributions if not dst and k == dst_str: 375*27b03b36SApple OSS Distributions dst = v 376*27b03b36SApple OSS Distributions if src and dst: 377*27b03b36SApple OSS Distributions break 378*27b03b36SApple OSS Distributions if not src: 379*27b03b36SApple OSS Distributions src = IPCNode(src_str) 380*27b03b36SApple OSS Distributions self.nodes[src_str] = src; 381*27b03b36SApple OSS Distributions if not dst: 382*27b03b36SApple OSS Distributions dst = IPCNode(dst_str) 383*27b03b36SApple OSS Distributions self.nodes[dst_str] = dst 384*27b03b36SApple OSS Distributions src.addpid(src_pid, time) 385*27b03b36SApple OSS Distributions dst.addpid(dst_pid, time) 386*27b03b36SApple OSS Distributions 387*27b03b36SApple OSS Distributions nm = self.edgename(src, dst) 388*27b03b36SApple OSS Distributions msgdata = {} 389*27b03b36SApple OSS Distributions msgDtype = {} 390*27b03b36SApple OSS Distributions e = self.edges.get(nm) 391*27b03b36SApple OSS Distributions if e != None: 392*27b03b36SApple OSS Distributions if e.ename() != nm: 393*27b03b36SApple OSS Distributions raise EdgeError(e,nm) 394*27b03b36SApple OSS Distributions msgdata, msgDtype = e.addmsg(data_hex_str, flags_str, time) 395*27b03b36SApple OSS Distributions else: 396*27b03b36SApple OSS Distributions e = IPCEdge(src, dst, data_hex_str, flags_str, time) 397*27b03b36SApple OSS Distributions msgdata, msgDtype = e.msgdata() 398*27b03b36SApple OSS Distributions self.edges[nm] = e 399*27b03b36SApple OSS Distributions 400*27b03b36SApple OSS Distributions if self.maxdweight < e.dweight: 401*27b03b36SApple OSS Distributions self.maxdweight = e.dweight 402*27b03b36SApple OSS Distributions 403*27b03b36SApple OSS Distributions if sum(msgdata.values()) == 0: 404*27b03b36SApple OSS Distributions self.msgs[0]['std'] += 1 405*27b03b36SApple OSS Distributions self.msgtypes[0]['std'] += 1 406*27b03b36SApple OSS Distributions if not 'enames' in self.msgs[0]: 407*27b03b36SApple OSS Distributions self.msgs[0]['enames'] = [ nm ] 408*27b03b36SApple OSS Distributions elif not nm in self.msgs[0]['enames']: 409*27b03b36SApple OSS Distributions self.msgs[0]['enames'].append(nm) 410*27b03b36SApple OSS Distributions else: 411*27b03b36SApple OSS Distributions for k,d in msgdata.iteritems(): 412*27b03b36SApple OSS Distributions if d > 0: 413*27b03b36SApple OSS Distributions self.msgs[d][k] += 1 414*27b03b36SApple OSS Distributions self.totals['n'+k] += 1 415*27b03b36SApple OSS Distributions self.totals['D'+k] += d 416*27b03b36SApple OSS Distributions if not 'enames' in self.msgs[d]: 417*27b03b36SApple OSS Distributions self.msgs[d]['enames'] = [ nm ] 418*27b03b36SApple OSS Distributions elif not nm in self.msgs[d]['enames']: 419*27b03b36SApple OSS Distributions self.msgs[d]['enames'].append(nm) 420*27b03b36SApple OSS Distributions for k,d in msgDtype.iteritems(): 421*27b03b36SApple OSS Distributions if d > 0: 422*27b03b36SApple OSS Distributions self.msgtypes[d][k] += 1 423*27b03b36SApple OSS Distributions self.nmsgs += 1 424*27b03b36SApple OSS Distributions if self.nmsgs % 1024 == 0: 425*27b03b36SApple OSS Distributions sys.stderr.write(" {:d}...\r".format(self.nmsgs)); 426*27b03b36SApple OSS Distributions 427*27b03b36SApple OSS Distributions def print_dot_node(self, ofile, node): 428*27b03b36SApple OSS Distributions omsgs, imsgs = node.nmsgs() 429*27b03b36SApple OSS Distributions recycled = node.recycled() * 5 430*27b03b36SApple OSS Distributions tcolor = 'black' 431*27b03b36SApple OSS Distributions if recycled >= 50: 432*27b03b36SApple OSS Distributions tcolor = 'white' 433*27b03b36SApple OSS Distributions if recycled == 5: 434*27b03b36SApple OSS Distributions bgcolor = 'white' 435*27b03b36SApple OSS Distributions elif recycled <= 100: 436*27b03b36SApple OSS Distributions bgcolor = 'grey{:d}'.format(100 - recycled) 437*27b03b36SApple OSS Distributions else: 438*27b03b36SApple OSS Distributions bgcolor = 'red' 439*27b03b36SApple OSS Distributions ofile.write("\t{:s} [style=filled,fontcolor={:s},fillcolor={:s},label=\"{:s}\"];\n"\ 440*27b03b36SApple OSS Distributions .format(node.nname, tcolor, bgcolor, node.label())) 441*27b03b36SApple OSS Distributions 442*27b03b36SApple OSS Distributions def print_dot_edge(self, nm, edge, ofile): 443*27b03b36SApple OSS Distributions #weight = 100 * edge.dweight / self.maxdweight 444*27b03b36SApple OSS Distributions ##if weight < 1: 445*27b03b36SApple OSS Distributions # weight = 1 446*27b03b36SApple OSS Distributions weight = edge.dweight 447*27b03b36SApple OSS Distributions penwidth = edge.weight / 512 448*27b03b36SApple OSS Distributions if penwidth < 0.5: 449*27b03b36SApple OSS Distributions penwidth = 0.5 450*27b03b36SApple OSS Distributions if penwidth > 7.99: 451*27b03b36SApple OSS Distributions penwidth = 8 452*27b03b36SApple OSS Distributions attrs = "weight={},penwidth={}".format(round(weight,2), round(penwidth,2)) 453*27b03b36SApple OSS Distributions 454*27b03b36SApple OSS Distributions if edge.flags & edge.F_RAISEIMP: 455*27b03b36SApple OSS Distributions attrs += ",arrowhead=dot" 456*27b03b36SApple OSS Distributions 457*27b03b36SApple OSS Distributions xpc = edge.dtype('xpc') + edge.dtype('xpc.reply') 458*27b03b36SApple OSS Distributions iokit = edge.dtype('iokit') + edge.dtype('iokit.reply') 459*27b03b36SApple OSS Distributions std = edge.dtype('std') + edge.dtype('std.reply') 460*27b03b36SApple OSS Distributions if xpc > (iokit + std): 461*27b03b36SApple OSS Distributions attrs += ',color=blue' 462*27b03b36SApple OSS Distributions elif iokit > (std + xpc): 463*27b03b36SApple OSS Distributions attrs += ',color=red' 464*27b03b36SApple OSS Distributions 465*27b03b36SApple OSS Distributions if edge.data('vcpy') > (edge.data('ool') + edge.data('std')): 466*27b03b36SApple OSS Distributions attrs += ',style="dotted"' 467*27b03b36SApple OSS Distributions """ # block comment 468*27b03b36SApple OSS Distributions ltype = [] 469*27b03b36SApple OSS Distributions if edge.flags & (edge.F_DST_NDFLTQ | edge.F_SRC_NDFLTQ): 470*27b03b36SApple OSS Distributions ltype.append('dotted') 471*27b03b36SApple OSS Distributions if edge.flags & edge.F_APP_SRC: 472*27b03b36SApple OSS Distributions ltype.append('bold') 473*27b03b36SApple OSS Distributions if len(ltype) > 0: 474*27b03b36SApple OSS Distributions attrs += ',style="' + reduce(lambda a, v: a + ',' + v, ltype) + '"' 475*27b03b36SApple OSS Distributions 476*27b03b36SApple OSS Distributions if edge.data('ool') > (edge.data('std') + edge.data('vcpy')): 477*27b03b36SApple OSS Distributions attrs += ",color=blue" 478*27b03b36SApple OSS Distributions if edge.data('vcpy') > (edge.data('ool') + edge.data('std')): 479*27b03b36SApple OSS Distributions attrs += ",color=green" 480*27b03b36SApple OSS Distributions """ 481*27b03b36SApple OSS Distributions 482*27b03b36SApple OSS Distributions ofile.write("\t{:s} [{:s}];\n".format(nm, attrs)) 483*27b03b36SApple OSS Distributions 484*27b03b36SApple OSS Distributions def print_follow_graph(self, ofile, follow, visited = None): 485*27b03b36SApple OSS Distributions ofile.write("digraph {:s} {{\n".format(self.name)) 486*27b03b36SApple OSS Distributions ofile.write("\tsplines=ortho;\n") 487*27b03b36SApple OSS Distributions if not visited: 488*27b03b36SApple OSS Distributions visited = [] 489*27b03b36SApple OSS Distributions for f in follow: 490*27b03b36SApple OSS Distributions sys.stderr.write("following {}\n".format(f)) 491*27b03b36SApple OSS Distributions lvl = 0 492*27b03b36SApple OSS Distributions printedges = {} 493*27b03b36SApple OSS Distributions while len(follow) > 0: 494*27b03b36SApple OSS Distributions cnodes = [] 495*27b03b36SApple OSS Distributions for nm, e in self.edges.iteritems(): 496*27b03b36SApple OSS Distributions nicename = e.src.nicename 497*27b03b36SApple OSS Distributions # Find all nodes to which 'follow' nodes communicate 498*27b03b36SApple OSS Distributions if e.src.nicename in follow: 499*27b03b36SApple OSS Distributions printedges[nm] = e 500*27b03b36SApple OSS Distributions if not e.selfedge() and not e.dst in cnodes: 501*27b03b36SApple OSS Distributions cnodes.append(e.dst) 502*27b03b36SApple OSS Distributions visited.extend(follow) 503*27b03b36SApple OSS Distributions follow = [] 504*27b03b36SApple OSS Distributions for n in cnodes: 505*27b03b36SApple OSS Distributions if not n.nicename in visited: 506*27b03b36SApple OSS Distributions follow.append(n.nicename) 507*27b03b36SApple OSS Distributions lvl += 1 508*27b03b36SApple OSS Distributions for f in follow: 509*27b03b36SApple OSS Distributions sys.stderr.write("{}following {}\n".format(' |--'*lvl, f)) 510*27b03b36SApple OSS Distributions # END: while len(follow) 511*27b03b36SApple OSS Distributions for k, v in self.nodes.iteritems(): 512*27b03b36SApple OSS Distributions if v.nicename in visited: 513*27b03b36SApple OSS Distributions self.print_dot_node(ofile, v) 514*27b03b36SApple OSS Distributions for nm, edge in printedges.iteritems(): 515*27b03b36SApple OSS Distributions self.print_dot_edge(nm, edge, ofile) 516*27b03b36SApple OSS Distributions ofile.write("}\n\n") 517*27b03b36SApple OSS Distributions 518*27b03b36SApple OSS Distributions def print_graph(self, ofile, follow): 519*27b03b36SApple OSS Distributions ofile.write("digraph {:s} {{\n".format(self.name)) 520*27b03b36SApple OSS Distributions ofile.write("\tsplines=ortho;\n") 521*27b03b36SApple OSS Distributions for k, v in self.nodes.iteritems(): 522*27b03b36SApple OSS Distributions self.print_dot_node(ofile, v) 523*27b03b36SApple OSS Distributions for nm, edge in self.edges.iteritems(): 524*27b03b36SApple OSS Distributions self.print_dot_edge(nm, edge, ofile) 525*27b03b36SApple OSS Distributions ofile.write("}\n\n") 526*27b03b36SApple OSS Distributions 527*27b03b36SApple OSS Distributions def print_nodegrid(self, ofile, type='msg', dfilter=None): 528*27b03b36SApple OSS Distributions showdata = False 529*27b03b36SApple OSS Distributions dfname = dfilter 530*27b03b36SApple OSS Distributions if not dfname: 531*27b03b36SApple OSS Distributions dfname = 'all' 532*27b03b36SApple OSS Distributions if type == 'data': 533*27b03b36SApple OSS Distributions showdata = True 534*27b03b36SApple OSS Distributions ofile.write("{} Data sent between nodes.\nRow == SOURCE; Column == DESTINATION\n".format(dfname)) 535*27b03b36SApple OSS Distributions else: 536*27b03b36SApple OSS Distributions ofile.write("{} Messages sent between nodes.\nRow == SOURCE; Column == DESTINATION\n".format(dfname)) 537*27b03b36SApple OSS Distributions 538*27b03b36SApple OSS Distributions if not dfilter: 539*27b03b36SApple OSS Distributions dfilter = IPCEdge.DTYPES 540*27b03b36SApple OSS Distributions ofile.write(' ,' + ','.join(self.nodes.keys()) + '\n') 541*27b03b36SApple OSS Distributions for snm, src in self.nodes.iteritems(): 542*27b03b36SApple OSS Distributions odata = [] 543*27b03b36SApple OSS Distributions for dnm, dst in self.nodes.iteritems(): 544*27b03b36SApple OSS Distributions enm = self.edgename(src, dst) 545*27b03b36SApple OSS Distributions e = self.edges.get(enm) 546*27b03b36SApple OSS Distributions if e and enm in src.outgoing.keys(): 547*27b03b36SApple OSS Distributions if showdata: 548*27b03b36SApple OSS Distributions dsize = reduce(lambda accum, t: accum + e.dtype(t), dfilter, 0) 549*27b03b36SApple OSS Distributions odata.append('{:d}'.format(dsize)) 550*27b03b36SApple OSS Distributions else: 551*27b03b36SApple OSS Distributions nmsg = reduce(lambda accum, t: accum + e.mtype(t), dfilter, 0) 552*27b03b36SApple OSS Distributions odata.append('{:d}'.format(nmsg)) 553*27b03b36SApple OSS Distributions else: 554*27b03b36SApple OSS Distributions odata.append('0') 555*27b03b36SApple OSS Distributions ofile.write(snm + ',' + ','.join(odata) + '\n') 556*27b03b36SApple OSS Distributions 557*27b03b36SApple OSS Distributions def print_datasummary(self, ofile): 558*27b03b36SApple OSS Distributions m = {} 559*27b03b36SApple OSS Distributions for type in IPCEdge.DTYPES: 560*27b03b36SApple OSS Distributions m[type] = [0, 0] 561*27b03b36SApple OSS Distributions for k, v in self.edges.iteritems(): 562*27b03b36SApple OSS Distributions for t in IPCEdge.DTYPES: 563*27b03b36SApple OSS Distributions m[t][0] += v.mtype(t) 564*27b03b36SApple OSS Distributions m[t][1] += v.dtype(t) 565*27b03b36SApple OSS Distributions tdata = 0 566*27b03b36SApple OSS Distributions tmsgs = 0 567*27b03b36SApple OSS Distributions for f in IPCEdge.DFLAVORS: 568*27b03b36SApple OSS Distributions tdata += self.totals['D'+f] 569*27b03b36SApple OSS Distributions tmsgs += self.totals['n'+f] 570*27b03b36SApple OSS Distributions # we account for 0-sized messages differently 571*27b03b36SApple OSS Distributions tmsgs += self.msgs[0]['std'] 572*27b03b36SApple OSS Distributions ofile.write("Nodes:{:d}\nEdges:{:d}\n".format(len(self.nodes),len(self.edges))) 573*27b03b36SApple OSS Distributions ofile.write("Total Messages,{}\nTotal Data,{}\n".format(tmsgs, tdata)) 574*27b03b36SApple OSS Distributions ofile.write("Flavor,Messages,Data,\n") 575*27b03b36SApple OSS Distributions for f in IPCEdge.DFLAVORS: 576*27b03b36SApple OSS Distributions ofile.write("{:s},{:d},{:d}\n".format(f, self.totals['n'+f], self.totals['D'+f])) 577*27b03b36SApple OSS Distributions ofile.write("Style,Messages,Data,\n") 578*27b03b36SApple OSS Distributions for t in IPCEdge.DTYPES: 579*27b03b36SApple OSS Distributions ofile.write("{:s},{:d},{:d}\n".format(t, m[t][0], m[t][1])) 580*27b03b36SApple OSS Distributions 581*27b03b36SApple OSS Distributions def print_freqdata(self, ofile, gnuplot = False): 582*27b03b36SApple OSS Distributions flavoridx = {} 583*27b03b36SApple OSS Distributions ostr = "Message Size" 584*27b03b36SApple OSS Distributions idx = 1 585*27b03b36SApple OSS Distributions for f in IPCEdge.DFLAVORS: 586*27b03b36SApple OSS Distributions ostr += ',{fmt:s} Freq,{fmt:s} CDF,{fmt:s} Data CDF,{fmt:s} Cumulative Data'.format(fmt=f) 587*27b03b36SApple OSS Distributions idx += 1 588*27b03b36SApple OSS Distributions flavoridx[f] = idx 589*27b03b36SApple OSS Distributions idx += 3 590*27b03b36SApple OSS Distributions ostr += ',#Unique SVC pairs\n' 591*27b03b36SApple OSS Distributions ofile.write(ostr) 592*27b03b36SApple OSS Distributions 593*27b03b36SApple OSS Distributions lastmsg = 0 594*27b03b36SApple OSS Distributions maxmsgs = {} 595*27b03b36SApple OSS Distributions totalmsgs = {} 596*27b03b36SApple OSS Distributions Tdata = {} 597*27b03b36SApple OSS Distributions for f in IPCEdge.DFLAVORS: 598*27b03b36SApple OSS Distributions maxmsgs[f] = 0 599*27b03b36SApple OSS Distributions totalmsgs[f] = 0 600*27b03b36SApple OSS Distributions Tdata[f] = 0 601*27b03b36SApple OSS Distributions 602*27b03b36SApple OSS Distributions for k, v in sorted(self.msgs.iteritems()): 603*27b03b36SApple OSS Distributions lastmsg = k 604*27b03b36SApple OSS Distributions _nmsgs = {} 605*27b03b36SApple OSS Distributions for f in IPCEdge.DFLAVORS: 606*27b03b36SApple OSS Distributions _nmsgs[f] = v[f] 607*27b03b36SApple OSS Distributions if v[f] > maxmsgs[f]: 608*27b03b36SApple OSS Distributions maxmsgs[f] = v[f] 609*27b03b36SApple OSS Distributions if k > 0: 610*27b03b36SApple OSS Distributions Tdata[f] += v[f] * k 611*27b03b36SApple OSS Distributions totalmsgs[f] += v[f] 612*27b03b36SApple OSS Distributions 613*27b03b36SApple OSS Distributions cdf = {f:0 for f in IPCEdge.DFLAVORS} 614*27b03b36SApple OSS Distributions dcdf = {f:0 for f in IPCEdge.DFLAVORS} 615*27b03b36SApple OSS Distributions if k > 0: # Only use messages with data size > 0 616*27b03b36SApple OSS Distributions for f in IPCEdge.DFLAVORS: 617*27b03b36SApple OSS Distributions if self.totals['n'+f] > 0: 618*27b03b36SApple OSS Distributions cdf[f] = int(100 * totalmsgs[f] / self.totals['n'+f]) 619*27b03b36SApple OSS Distributions if self.totals['D'+f] > 0: 620*27b03b36SApple OSS Distributions dcdf[f] = int(100 * Tdata[f] / self.totals['D'+f]) 621*27b03b36SApple OSS Distributions 622*27b03b36SApple OSS Distributions ostr = "{:d}".format(k) 623*27b03b36SApple OSS Distributions for f in IPCEdge.DFLAVORS: 624*27b03b36SApple OSS Distributions ostr += ",{:d},{:d},{:d},{:d}".format(_nmsgs[f],cdf[f],dcdf[f],Tdata[f]) 625*27b03b36SApple OSS Distributions ostr += ",{:d}\n".format(len(v['enames'])) 626*27b03b36SApple OSS Distributions ofile.write(ostr) 627*27b03b36SApple OSS Distributions 628*27b03b36SApple OSS Distributions if not gnuplot: 629*27b03b36SApple OSS Distributions return 630*27b03b36SApple OSS Distributions 631*27b03b36SApple OSS Distributions colors = [ 'blue', 'red', 'green', 'black', 'grey', 'yellow' ] 632*27b03b36SApple OSS Distributions idx = 0 633*27b03b36SApple OSS Distributions flavorcolor = {} 634*27b03b36SApple OSS Distributions maxdata = 0 635*27b03b36SApple OSS Distributions maxmsg = max(maxmsgs.values()) 636*27b03b36SApple OSS Distributions for f in IPCEdge.DFLAVORS: 637*27b03b36SApple OSS Distributions flavorcolor[f] = colors[idx] 638*27b03b36SApple OSS Distributions if self.totals['D'+f] > maxdata: 639*27b03b36SApple OSS Distributions maxdata = self.totals['D'+f] 640*27b03b36SApple OSS Distributions idx += 1 641*27b03b36SApple OSS Distributions 642*27b03b36SApple OSS Distributions sys.stderr.write("Creating GNUPlot...\n") 643*27b03b36SApple OSS Distributions 644*27b03b36SApple OSS Distributions cdf_data_fmt = """\ 645*27b03b36SApple OSS Distributions set terminal postscript eps enhanced color solid 'Courier' 12 646*27b03b36SApple OSS Distributions set border 3 647*27b03b36SApple OSS Distributions set size 1.5, 1.5 648*27b03b36SApple OSS Distributions set xtics nomirror 649*27b03b36SApple OSS Distributions set ytics nomirror 650*27b03b36SApple OSS Distributions set xrange [1:2048] 651*27b03b36SApple OSS Distributions set yrange [0:100] 652*27b03b36SApple OSS Distributions set ylabel font 'Courier,14' "Total Message CDF\\n(% of total number of messages)" 653*27b03b36SApple OSS Distributions set xlabel font 'Courier,14' "Message Size (bytes)" 654*27b03b36SApple OSS Distributions set datafile separator "," 655*27b03b36SApple OSS Distributions set ytics ( '0' 0, '10' 10, '20' 20, '30' 30, '40' 40, '50' 50, '60' 60, '70' 70, '80' 80, '90' 90, '100' 100) 656*27b03b36SApple OSS Distributions plot """ 657*27b03b36SApple OSS Distributions plots = [] 658*27b03b36SApple OSS Distributions for f in IPCEdge.DFLAVORS: 659*27b03b36SApple OSS Distributions plots.append("'{{csvfile:s}}' using 1:{:d} title '{:s} Messages' with lines lw 2 lt 1 lc rgb \"{:s}\"".format(flavoridx[f]+1, f, flavorcolor[f])) 660*27b03b36SApple OSS Distributions cdf_data_fmt += ', \\\n'.join(plots) 661*27b03b36SApple OSS Distributions 662*27b03b36SApple OSS Distributions dcdf_data_fmt = """\ 663*27b03b36SApple OSS Distributions set terminal postscript eps enhanced color solid 'Courier' 12 664*27b03b36SApple OSS Distributions set border 3 665*27b03b36SApple OSS Distributions set size 1.5, 1.5 666*27b03b36SApple OSS Distributions set xtics nomirror 667*27b03b36SApple OSS Distributions set ytics nomirror 668*27b03b36SApple OSS Distributions set xrange [1:32768] 669*27b03b36SApple OSS Distributions set yrange [0:100] 670*27b03b36SApple OSS Distributions set ylabel font 'Courier,14' "Total Data CDF\\n(% of total data transmitted)" 671*27b03b36SApple OSS Distributions set xlabel font 'Courier,14' "Message Size (bytes)" 672*27b03b36SApple OSS Distributions set datafile separator "," 673*27b03b36SApple OSS Distributions set ytics ( '0' 0, '10' 10, '20' 20, '30' 30, '40' 40, '50' 50, '60' 60, '70' 70, '80' 80, '90' 90, '100' 100) 674*27b03b36SApple OSS Distributions plot """ 675*27b03b36SApple OSS Distributions plots = [] 676*27b03b36SApple OSS Distributions for f in IPCEdge.DFLAVORS: 677*27b03b36SApple OSS Distributions plots.append("'{{csvfile:s}}' using 1:{:d} title '{:s} Message Data' with lines lw 2 lt 1 lc rgb \"{:s}\"".format(flavoridx[f]+2, f, flavorcolor[f])) 678*27b03b36SApple OSS Distributions dcdf_data_fmt += ', \\\n'.join(plots) 679*27b03b36SApple OSS Distributions 680*27b03b36SApple OSS Distributions freq_data_fmt = """\ 681*27b03b36SApple OSS Distributions set terminal postscript eps enhanced color solid 'Courier' 12 682*27b03b36SApple OSS Distributions set size 1.5, 1.5 683*27b03b36SApple OSS Distributions set xrange [1:32768] 684*27b03b36SApple OSS Distributions set yrange [0:9000] 685*27b03b36SApple OSS Distributions set x2range [1:32768] 686*27b03b36SApple OSS Distributions set y2range [0:{maxdata:d}] 687*27b03b36SApple OSS Distributions set xtics nomirror 688*27b03b36SApple OSS Distributions set ytics nomirror 689*27b03b36SApple OSS Distributions set y2tics 690*27b03b36SApple OSS Distributions set autoscale y2 691*27b03b36SApple OSS Distributions set grid x y2 692*27b03b36SApple OSS Distributions set ylabel font 'Courier,14' "Number of Messages" 693*27b03b36SApple OSS Distributions set y2label font 'Courier,14' "Data Transferred (bytes)" 694*27b03b36SApple OSS Distributions set xlabel font 'Courier,14' "Message Size (bytes)" 695*27b03b36SApple OSS Distributions set datafile separator "," 696*27b03b36SApple OSS Distributions set tics out 697*27b03b36SApple OSS Distributions set boxwidth 1 698*27b03b36SApple OSS Distributions set style fill solid 699*27b03b36SApple OSS Distributions plot """ 700*27b03b36SApple OSS Distributions plots = [] 701*27b03b36SApple OSS Distributions for f in IPCEdge.DFLAVORS: 702*27b03b36SApple OSS Distributions plots.append("'{{csvfile:s}}' using 1:{:d} axes x1y1 title '{:s} Messages' with boxes lt 1 lc rgb \"{:s}\"".format(flavoridx[f], f, flavorcolor[f])) 703*27b03b36SApple OSS Distributions plots.append("'{{csvfile:s}}' using 1:{:d} axes x2y2 title '{:s} Data' with line lt 1 lw 2 lc rgb \"{:s}\"".format(flavoridx[f]+3, f, flavorcolor[f])) 704*27b03b36SApple OSS Distributions freq_data_fmt += ', \\\n'.join(plots) 705*27b03b36SApple OSS Distributions try: 706*27b03b36SApple OSS Distributions new_file = re.sub(r'(.*)\.\w+$', r'\1_cdf.plot', ofile.name) 707*27b03b36SApple OSS Distributions sys.stderr.write("\t{:s}...\n".format(new_file)) 708*27b03b36SApple OSS Distributions plotfile = open(new_file, 'w') 709*27b03b36SApple OSS Distributions plotfile.write(cdf_data_fmt.format(lastmsg=lastmsg, maxdata=maxdata, maxmsg=maxmsg, csvfile=ofile.name)) 710*27b03b36SApple OSS Distributions plotfile.flush() 711*27b03b36SApple OSS Distributions plotfile.close() 712*27b03b36SApple OSS Distributions 713*27b03b36SApple OSS Distributions new_file = re.sub(r'(.*)\.\w+$', r'\1_dcdf.plot', ofile.name) 714*27b03b36SApple OSS Distributions sys.stderr.write("\t{:s}...\n".format(new_file)) 715*27b03b36SApple OSS Distributions plotfile = open(new_file, 'w') 716*27b03b36SApple OSS Distributions plotfile.write(dcdf_data_fmt.format(lastmsg=lastmsg, maxdata=maxdata, maxmsg=maxmsg, csvfile=ofile.name)) 717*27b03b36SApple OSS Distributions plotfile.flush() 718*27b03b36SApple OSS Distributions plotfile.close() 719*27b03b36SApple OSS Distributions 720*27b03b36SApple OSS Distributions new_file = re.sub(r'(.*)\.\w+$', r'\1_hist.plot', ofile.name) 721*27b03b36SApple OSS Distributions sys.stderr.write("\t{:s}...\n".format(new_file)) 722*27b03b36SApple OSS Distributions plotfile = open(new_file, 'w') 723*27b03b36SApple OSS Distributions plotfile.write(freq_data_fmt.format(lastmsg=lastmsg, maxdata=maxdata, maxmsg=maxmsg, csvfile=ofile.name)) 724*27b03b36SApple OSS Distributions plotfile.flush() 725*27b03b36SApple OSS Distributions plotfile.close() 726*27b03b36SApple OSS Distributions except: 727*27b03b36SApple OSS Distributions sys.stderr.write("\nFailed to write gnuplot script!\n"); 728*27b03b36SApple OSS Distributions return 729*27b03b36SApple OSS Distributions 730*27b03b36SApple OSS Distributions 731*27b03b36SApple OSS Distributionsdef convert_raw_tracefiles(args): 732*27b03b36SApple OSS Distributions if not args.raw or len(args.raw) < 1: 733*27b03b36SApple OSS Distributions return 734*27b03b36SApple OSS Distributions 735*27b03b36SApple OSS Distributions if not args.tracefile: 736*27b03b36SApple OSS Distributions args.tracefile = [] 737*27b03b36SApple OSS Distributions 738*27b03b36SApple OSS Distributions for rawfile in args.raw: 739*27b03b36SApple OSS Distributions sys.stderr.write("Converting RAW tracefile '{:s}'...\n".format(rawfile.name)) 740*27b03b36SApple OSS Distributions if args.tbfreq and len(args.tbfreq) > 0: 741*27b03b36SApple OSS Distributions args.tbfreq = " -F " + args.tbfreq 742*27b03b36SApple OSS Distributions else: 743*27b03b36SApple OSS Distributions args.tbfreq = "" 744*27b03b36SApple OSS Distributions tfile = re.sub(r'(.*)(\.\w+)*$', r'\1.ascii', rawfile.name) 745*27b03b36SApple OSS Distributions cmd = 'trace -R {:s}{:s} -o {:s}'.format(rawfile.name, args.tbfreq, tfile) 746*27b03b36SApple OSS Distributions if args.tracecodes and len(args.tracecodes) > 0: 747*27b03b36SApple OSS Distributions cmd += " -N {}".format(args.tracecodes[0]) 748*27b03b36SApple OSS Distributions elif os.path.isfile('bsd/kern/trace.codes'): 749*27b03b36SApple OSS Distributions cmd += " -N bsd/kern/trace.codes" 750*27b03b36SApple OSS Distributions if args.traceargs and len(args.traceargs) > 0: 751*27b03b36SApple OSS Distributions cmd += ' '.join(args.traceargs) 752*27b03b36SApple OSS Distributions (ret, outstr) = RunCommand(cmd) 753*27b03b36SApple OSS Distributions if ret != 0: 754*27b03b36SApple OSS Distributions os.stderr.write("Couldn't convert raw trace file. ret=={:d}\nE: {:s}\n".format(ret, outstr)) 755*27b03b36SApple OSS Distributions sys.exit(ret) 756*27b03b36SApple OSS Distributions 757*27b03b36SApple OSS Distributions if not os.path.isfile(tfile): 758*27b03b36SApple OSS Distributions sys.stderr.write("Failure to convert raw trace file '{:s}'\ncmd: '{:s}'\n".format(args.raw[0].name, cmd)) 759*27b03b36SApple OSS Distributions sys.exit(1) 760*27b03b36SApple OSS Distributions args.tracefile.append(open(tfile, 'r')) 761*27b03b36SApple OSS Distributions # END: for rawfile in args.raw 762*27b03b36SApple OSS Distributions 763*27b03b36SApple OSS Distributions 764*27b03b36SApple OSS Distributionsdef parse_tracefile_line(line, exclude, include, exflags, incflags, active_proc, graph, base=16): 765*27b03b36SApple OSS Distributions val = line.split() 766*27b03b36SApple OSS Distributions if len(val) < 10: 767*27b03b36SApple OSS Distributions return 768*27b03b36SApple OSS Distributions if val[2] == "proc_exec" or val[2] == "TRACE_DATA_EXEC": 769*27b03b36SApple OSS Distributions pid = int(val[3], base) 770*27b03b36SApple OSS Distributions active_proc[pid] = val[9] 771*27b03b36SApple OSS Distributions if val[2] == "MACH_IPC_kmsg_info": 772*27b03b36SApple OSS Distributions sendpid = int(val[3], base) 773*27b03b36SApple OSS Distributions destpid = int(val[4], base) 774*27b03b36SApple OSS Distributions if sendpid == 0: 775*27b03b36SApple OSS Distributions src = "kernel_task" 776*27b03b36SApple OSS Distributions elif sendpid in active_proc: 777*27b03b36SApple OSS Distributions src = active_proc[sendpid] 778*27b03b36SApple OSS Distributions else: 779*27b03b36SApple OSS Distributions src = "{:d}".format(sendpid) 780*27b03b36SApple OSS Distributions if destpid == 0: 781*27b03b36SApple OSS Distributions dst = "kernel_task" 782*27b03b36SApple OSS Distributions elif destpid in active_proc: 783*27b03b36SApple OSS Distributions dst = active_proc[destpid] 784*27b03b36SApple OSS Distributions else: 785*27b03b36SApple OSS Distributions dst = "{:d}".format(destpid) 786*27b03b36SApple OSS Distributions if exclude and len(exclude) > 0 and (src in exclude or dst in exclude): 787*27b03b36SApple OSS Distributions return 788*27b03b36SApple OSS Distributions if include and len(include) > 0 and (not (src in include or dst in include)): 789*27b03b36SApple OSS Distributions return 790*27b03b36SApple OSS Distributions flags = int(val[6], 16) 791*27b03b36SApple OSS Distributions if exflags or incflags: 792*27b03b36SApple OSS Distributions if exflags and (flags & int(exflags[0], 0)): 793*27b03b36SApple OSS Distributions return 794*27b03b36SApple OSS Distributions if incflags and (flags & int(incflags[0], 0)) != int(incflags[0], 0): 795*27b03b36SApple OSS Distributions return 796*27b03b36SApple OSS Distributions # create a graph edge 797*27b03b36SApple OSS Distributions if (flags & IPCEdge.F_TRACED): 798*27b03b36SApple OSS Distributions graph.addmsg(src, sendpid, dst, destpid, val[5], val[6], float(val[0])) 799*27b03b36SApple OSS Distributions # END: MACH_IPC_kmsg_info 800*27b03b36SApple OSS Distributions 801*27b03b36SApple OSS Distributions# 802*27b03b36SApple OSS Distributions# Main 803*27b03b36SApple OSS Distributions# 804*27b03b36SApple OSS Distributionsdef main(argv=sys.argv): 805*27b03b36SApple OSS Distributions """ Main program entry point. 806*27b03b36SApple OSS Distributions 807*27b03b36SApple OSS Distributions Trace file output lines look like this: 808*27b03b36SApple OSS Distributions {abstime} {delta} MACH_IPC_kmsg_info {src_pid} {dst_pid} {msg_len} {flags} {threadid} {cpu} {proc_name} 809*27b03b36SApple OSS Distributions e.g. 810*27b03b36SApple OSS Distributions 4621921.2 33.8(0.0) MACH_IPC_kmsg_info ac 9d c 230002 b2e 1 MobileMail 811*27b03b36SApple OSS Distributions 812*27b03b36SApple OSS Distributions Or like this: 813*27b03b36SApple OSS Distributions {abstime} {delta} proc_exec {pid} 0 0 0 {threadid} {cpu} {proc_name} 814*27b03b36SApple OSS Distributions e.g. 815*27b03b36SApple OSS Distributions 4292212.3 511.2 proc_exec c8 0 0 0 b44 0 voiced 816*27b03b36SApple OSS Distributions """ 817*27b03b36SApple OSS Distributions global g_verbose 818*27b03b36SApple OSS Distributions 819*27b03b36SApple OSS Distributions parser = argparse.ArgumentParser(description='Parse an XNU Mach IPC kmsg ktrace file') 820*27b03b36SApple OSS Distributions 821*27b03b36SApple OSS Distributions # output a DOT formatted graph file 822*27b03b36SApple OSS Distributions parser.add_argument('--printgraph', '-g', dest='graph', default=None, type=argparse.FileType('w'), help='Output a DOT connectivity graph from the trace data') 823*27b03b36SApple OSS Distributions parser.add_argument('--graphname', dest='name', default='ipcgraph', help='A name for the DOT graph output') 824*27b03b36SApple OSS Distributions parser.add_argument('--graphfollow', dest='follow', nargs='+', metavar='NAME', help='Graph only the transitive closure of services / processes which communicate with the given service(s)') 825*27b03b36SApple OSS Distributions 826*27b03b36SApple OSS Distributions # output a CDF of message data 827*27b03b36SApple OSS Distributions parser.add_argument('--printfreq', '-f', dest='freq', default=None, type=argparse.FileType('w'), help='Output a frequency distribution of message data (in CSV format)') 828*27b03b36SApple OSS Distributions parser.add_argument('--gnuplot', dest='gnuplot', action='store_true', help='Write out a gnuplot file along with the frequency distribution data') 829*27b03b36SApple OSS Distributions 830*27b03b36SApple OSS Distributions # output a simple summary of message data 831*27b03b36SApple OSS Distributions parser.add_argument('--printsummary', '-s', dest='summary', default=None, type=argparse.FileType('w'), help='Output a summary of all messages in the trace data') 832*27b03b36SApple OSS Distributions 833*27b03b36SApple OSS Distributions # Output a CSV grid of node data/messages 834*27b03b36SApple OSS Distributions parser.add_argument('--printnodegrid', '-n', dest='nodegrid', default=None, type=argparse.FileType('w'), help='Output a CSV grid of all messages/data sent between nodes (defaults to # messages)') 835*27b03b36SApple OSS Distributions parser.add_argument('--ngridtype', dest='ngridtype', default=None, choices=['msgs', 'data'], help='Used with the --printnodegrid argument, this option control whether the grid will be # of messages sent between nodes, or amount of data sent between nodes') 836*27b03b36SApple OSS Distributions parser.add_argument('--ngridfilter', dest='ngridfilter', default=None, nargs='+', choices=IPCEdge.DTYPES, help='Used with the --printnodegrid argument, this option controls the type of messages or data counted') 837*27b03b36SApple OSS Distributions 838*27b03b36SApple OSS Distributions parser.add_argument('--raw', '-R', dest='raw', nargs='+', type=argparse.FileType('r'), metavar='tracefile', help='Process a raw tracefile using the "trace" utility on the host. This requires an ssh connection to the device, or a manual specification of the tbfrequency.') 839*27b03b36SApple OSS Distributions parser.add_argument('--tbfreq', '-T', dest='tbfreq', default=None, help='The value of sysctl hw.tbfrequency run on the device') 840*27b03b36SApple OSS Distributions parser.add_argument('--device', '-D', dest='device', nargs=1, metavar='DEV', help='The name of the iOS device reachable via "ssh DEV"') 841*27b03b36SApple OSS Distributions parser.add_argument('--tracecodes', '-N', dest='tracecodes', nargs=1, metavar='TRACE.CODES', help='Path to a custom trace.codes file. By default, the script will look for bsd/kern/trace.codes from the current directory)') 842*27b03b36SApple OSS Distributions parser.add_argument('--traceargs', dest='traceargs', nargs='+', metavar='TRACE_OPT', help='Extra options to the "trace" program run on the host') 843*27b03b36SApple OSS Distributions 844*27b03b36SApple OSS Distributions parser.add_argument('--psfile', dest='psfile', nargs='+', type=argparse.FileType('r'), help='Process list file output by ios_trace_ipc.sh') 845*27b03b36SApple OSS Distributions 846*27b03b36SApple OSS Distributions parser.add_argument('--exclude', dest='exclude', metavar='NAME', nargs='+', help='List of services to exclude from processing. Any messages sent to or originating from these services will be discarded.') 847*27b03b36SApple OSS Distributions parser.add_argument('--include', dest='include', metavar='NAME', nargs='+', help='List of services to include in processing. Only messages sent to or originating from these services will be processed.') 848*27b03b36SApple OSS Distributions parser.add_argument('--exflags', dest='exflags', metavar='0xFLAGS', nargs=1, help='Messages with any of these flags bits set will be discarded') 849*27b03b36SApple OSS Distributions parser.add_argument('--incflags', dest='incflags', metavar='0xFLAGS', nargs=1, type=int, help='Only messages with all of these flags bits set will be processed') 850*27b03b36SApple OSS Distributions 851*27b03b36SApple OSS Distributions parser.add_argument('--verbose', '-v', dest='verbose', action='count', help='be verbose (can be used multiple times)') 852*27b03b36SApple OSS Distributions parser.add_argument('tracefile', nargs='*', type=argparse.FileType('r'), help='Input trace file') 853*27b03b36SApple OSS Distributions 854*27b03b36SApple OSS Distributions args = parser.parse_args() 855*27b03b36SApple OSS Distributions 856*27b03b36SApple OSS Distributions g_verbose = args.verbose 857*27b03b36SApple OSS Distributions 858*27b03b36SApple OSS Distributions if not args.graph and not args.freq and not args.summary and not args.nodegrid: 859*27b03b36SApple OSS Distributions sys.stderr.write("Please select at least one output format: [-gfsn] {file}\n") 860*27b03b36SApple OSS Distributions sys.exit(1) 861*27b03b36SApple OSS Distributions 862*27b03b36SApple OSS Distributions convert_raw_tracefiles(args) 863*27b03b36SApple OSS Distributions 864*27b03b36SApple OSS Distributions graph = IPCGraph(args.name, args.tbfreq) 865*27b03b36SApple OSS Distributions 866*27b03b36SApple OSS Distributions nfiles = len(args.tracefile) 867*27b03b36SApple OSS Distributions idx = 0 868*27b03b36SApple OSS Distributions while idx < nfiles: 869*27b03b36SApple OSS Distributions active_proc = {} 870*27b03b36SApple OSS Distributions # Parse a ps output file (generated by ios_trace_ipc.sh) 871*27b03b36SApple OSS Distributions # This pre-fills the active_proc list 872*27b03b36SApple OSS Distributions if args.psfile and len(args.psfile) > idx: 873*27b03b36SApple OSS Distributions sys.stderr.write("Parsing {:s}...\n".format(args.psfile[idx].name)) 874*27b03b36SApple OSS Distributions for line in args.psfile[idx]: 875*27b03b36SApple OSS Distributions if line.strip() == '': 876*27b03b36SApple OSS Distributions continue 877*27b03b36SApple OSS Distributions parse_tracefile_line(line.strip(), None, None, None, None, active_proc, graph, 10) 878*27b03b36SApple OSS Distributions # END: for line in psfile 879*27b03b36SApple OSS Distributions 880*27b03b36SApple OSS Distributions sys.stderr.write("Parsing {:s}...\n".format(args.tracefile[idx].name)) 881*27b03b36SApple OSS Distributions for line in args.tracefile[idx]: 882*27b03b36SApple OSS Distributions if line.strip() == '': 883*27b03b36SApple OSS Distributions continue 884*27b03b36SApple OSS Distributions parse_tracefile_line(line.strip(), args.exclude, args.include, args.exflags, args.incflags, active_proc, graph) 885*27b03b36SApple OSS Distributions # END: for line in tracefile 886*27b03b36SApple OSS Distributions idx += 1 887*27b03b36SApple OSS Distributions # END: foreach tracefile/psfile 888*27b03b36SApple OSS Distributions 889*27b03b36SApple OSS Distributions if args.graph: 890*27b03b36SApple OSS Distributions if args.follow and len(args.follow) > 0: 891*27b03b36SApple OSS Distributions sys.stderr.write("Writing follow-graph to {:s}...\n".format(args.graph.name)) 892*27b03b36SApple OSS Distributions graph.print_follow_graph(args.graph, args.follow) 893*27b03b36SApple OSS Distributions else: 894*27b03b36SApple OSS Distributions sys.stderr.write("Writing graph output to {:s}...\n".format(args.graph.name)) 895*27b03b36SApple OSS Distributions graph.print_graph(args.graph, args.follow) 896*27b03b36SApple OSS Distributions if args.freq: 897*27b03b36SApple OSS Distributions sys.stderr.write("Writing CDF data to {:s}...\n".format(args.freq.name)) 898*27b03b36SApple OSS Distributions graph.print_freqdata(args.freq, args.gnuplot) 899*27b03b36SApple OSS Distributions if args.summary: 900*27b03b36SApple OSS Distributions sys.stderr.write("Writing summary data to {:s}...\n".format(args.summary.name)) 901*27b03b36SApple OSS Distributions graph.print_datasummary(args.summary) 902*27b03b36SApple OSS Distributions if args.nodegrid: 903*27b03b36SApple OSS Distributions nm = args.ngridtype 904*27b03b36SApple OSS Distributions sys.stderr.write("Writing node grid data to {:s}...]\n".format(args.nodegrid.name)) 905*27b03b36SApple OSS Distributions graph.print_nodegrid(args.nodegrid, args.ngridtype, args.ngridfilter) 906*27b03b36SApple OSS Distributions 907*27b03b36SApple OSS Distributionsif __name__ == '__main__': 908*27b03b36SApple OSS Distributions sys.exit(main()) 909