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