Class: Fastlane::Helper::LinkMap::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/fastlane/plugin/analyze_ios_linkmap/helper/analyze_ios_linkmap_helper.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filepath) ⇒ Parser

Returns a new instance of Parser.



73
74
75
76
77
78
79
80
81
82
# File 'lib/fastlane/plugin/analyze_ios_linkmap/helper/analyze_ios_linkmap_helper.rb', line 73

def initialize(filepath)
  @filepath = filepath

  @object_map = {}
  @library_map = {}
  @section_map = {}
  @segment_map = {} # 根据 @section_map 统计【所有的 section】得出

  parse
end

Instance Attribute Details

#library_mapObject

Returns the value of attribute library_map.



71
72
73
# File 'lib/fastlane/plugin/analyze_ios_linkmap/helper/analyze_ios_linkmap_helper.rb', line 71

def library_map
  @library_map
end

#object_mapObject

Returns the value of attribute object_map.



71
72
73
# File 'lib/fastlane/plugin/analyze_ios_linkmap/helper/analyze_ios_linkmap_helper.rb', line 71

def object_map
  @object_map
end

#section_mapObject

Returns the value of attribute section_map.



71
72
73
# File 'lib/fastlane/plugin/analyze_ios_linkmap/helper/analyze_ios_linkmap_helper.rb', line 71

def section_map
  @section_map
end

#segment_mapObject

Returns the value of attribute segment_map.



71
72
73
# File 'lib/fastlane/plugin/analyze_ios_linkmap/helper/analyze_ios_linkmap_helper.rb', line 71

def segment_map
  @segment_map
end

Instance Method Details

#parseObject



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/fastlane/plugin/analyze_ios_linkmap/helper/analyze_ios_linkmap_helper.rb', line 84

def parse
  # 读取 Linkmap.txt 【每一行】进行解析
  File.foreach(@filepath).with_index do |line, line_num|
    begin
      unless line.valid_encoding?
        line = line.encode("UTF-16", :invalid => :replace, :replace => "?").encode('UTF-8')
      end
  
      if line.start_with? "#"
        if line.start_with? "# Object files:" #=> 初始化 @object_map
          @subparser = :parse_object_files
        elsif line.start_with? "# Sections:"  #=> 初始化 @section_map
          @subparser = :parse_sections
        elsif line.start_with? "# Symbols:"   #=> 解析得到每一个 symbol 【占用】大小
          @subparser = :parse_symbols
        elsif line.start_with? '# Dead Stripped Symbols:' #=> 解析得到 dead strpped 【废弃】大小
          @subparser = :parse_dead
        end
      else
        send(@subparser, line) #=> self.func(line)
      end
    rescue => e
      UI.error "Exception on Link map file line #{line_num}"
      UI.message "Content is: "
      UI.message line
    end
  end
  # puts "There are #{@section_map.values.map{|value| value[:residual_size]}.inject(:+)} Byte in some section can not be analyze"
end

#parse_dead(line) ⇒ Object



350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'lib/fastlane/plugin/analyze_ios_linkmap/helper/analyze_ios_linkmap_helper.rb', line 350

def parse_dead(line)
  # Dead Stripped Symbols:
  #           Size    	  File  Name
  # <<dead>> 	0x00000028	[  2] literal string: com.xxx.audioBook.notifications.start
  # <<dead>> 	0x00000029	[  2] literal string: com.xxx.audioBook.notifications.stoped
  # <<dead>> 	0x0000002A	[  2] literal string: com.xxx.audioBook.notificaitons.loading
  # <<dead>> 	0x0000002A	[  2] literal string: com.xxx.audioBook.notificaitons.palying
  # <<dead>> 	0x0000002D	[  2] literal string: com.xxx.audioBook.notificaitons.paySuccess
  # <<dead>> 	0x00000006	[  2] literal string: appId
  # <<dead>> 	0x00000008	[  2] literal string: fakeURL
  # <<dead>> 	0x00000007	[  2] literal string: 300300
  
  if line =~ %r(^<<dead>>\s+0x(.+?)\s+\[(.+?)\]\w*)
    size = $1.to_i(16)
    file = $2.to_i

    object_file = @object_map[file]
    return unless object_file
    
    # 累加 xx.o 的 dead symbol size
    object_file.dead_symbol_size += size

    # 累加 library(xx.o) 的 dead symbol size
    @library_map[object_file.library].dead_symbol_size += size
  end
end

#parse_object_files(line) ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/fastlane/plugin/analyze_ios_linkmap/helper/analyze_ios_linkmap_helper.rb', line 114

def parse_object_files(line)
  if line =~ %r(\[(.*)\].*\/(.*)\((.*)\))
    # Object files:
    # [  5] /Users/xiongzenghui/Desktop/launching_time/osee2unified/osee2unified/Pods/BangcleCryptoTool/BangcleCryptoTool/libs/libbangcle_crypto_tool.a(aes.o)
    # [  6] /Users/xiongzenghui/Desktop/launching_time/osee2unified/osee2unified/Pods/BangcleCryptoTool/BangcleCryptoTool/libs/libbangcle_crypto_tool.a(crypto.o)
    # [  7] /Users/xiongzenghui/Desktop/launching_time/osee2unified/osee2unified/Pods/BangcleCryptoTool/BangcleCryptoTool/libs/libbangcle_crypto_tool.a(des.o)
    # ...............
    # [ 23] /Users/xxx/ci-jenkins/workspace/xxx-iOS-module/VenomShellProject/osee2unified/Pods/AFNetworking/AFNetworking.framework/AFNetworking(AFAutoPurgingImageCache.o)
    # [ 24] /Users/xxx/ci-jenkins/workspace/xxx-iOS-module/VenomShellProject/osee2unified/Pods/AFNetworking/AFNetworking.framework/AFNetworking(AFHTTPSessionManager.o)
    # [ 25] /Users/xxx/ci-jenkins/workspace/xxx-iOS-module/VenomShellProject/osee2unified/Pods/AFNetworking/AFNetworking.framework/AFNetworking(AFImageDownloader.o)
    # ...........
  
    # 1.
    objc_file_id      = $1.to_i #=> 6 , 23
    library_name      = $2      #=> libbangcle_crypto_tool.a , AFNetworking
    object_file       = $3      #=> crypto.o , AFAutoPurgingImageCache.o

    # 2.
    of = ObjectFile.new(
      objc_file_id,
      object_file,
      library_name, 
      if line.include?('.framework')
        true
      else
        false
      end,
      Array.new,
      0,
      0
    )

    # 3. 保存解析 xx.o (object file) 的数据
    @object_map[objc_file_id] = of
  
    # 4. 创建【静态库 library】对应的实体对象
    library = @library_map[library_name]
    library ||= Library.new(library_name, 0, [], 0, '')
  
    # 5. 【追加】 xx.o 文件位于 ``# Object Files`` 后面的 [ n] 标号
    library.object_file_ids << objc_file_id
  
    # 6. 确认 library 的 pod_name 名字
    if line.include?('/Pods/')
      # [ 23] /Users/xxx/ci-jenkins/workspace/xxx-iOS-module/VenomShellProject/osee2unified/Pods/AFNetworking/AFNetworking.framework/AFNetworking(AFAutoPurgingImageCache.o)
      divstr = line.split('/Pods/').last  #=> AFNetworking/AFNetworking.framework/AFNetworking(AFAutoPurgingImageCache.o
      pod_name = divstr.split('/').first  #=> AFNetworking
      library.pod_name = pod_name
    else
      library.pod_name = ''
    end
  
    # 7. 
    @library_map[library_name] = library
  elsif line =~ %r(\[(.*)\].*\/(.*))
    # [  3] /SomePath/Release-iphoneos/CrashDemo.build/Objects-normal/arm64/main.o
    # [100] /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/UIKit.framework/UIKit.tbd
    # [9742] /SomePath/Pods/du.framework/du
    # [8659] /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos/libswiftDispatch.dylib
  
    # 1.
    objc_file_id  = $1.to_i #=> 3
    object_file   = $2  #=> main.o
  
    # 2.
    library_name = ''
    if line.include?('.framework') && !object_file.include?('.') #=> /path/to/du.framework/du 【用户】动态库
      library_name = object_file
    else
      if line.end_with?('.a')
        library_name = object_file
      else
        library_name = if object_file.end_with?('.tbd')
          'tdb'
        elsif object_file.end_with?('.dylib')
          'dylib'
        elsif object_file.end_with?('.o')
          'main'
        else
          'system'
        end
      end
    end

    # 3.
    of = ObjectFile.new(
      objc_file_id,
      object_file,
      library_name, 
      if line.include?('.framework') && !object_file.include?('.')
        true
      else
        false
      end,
      Array.new,
      0,
      0
    )
  
    # 4.
    @object_map[objc_file_id] = of
    # puts "#{objc_file_id} -- #{library_name}"

    # 5. 
    library = @library_map[library_name]
    library ||= Library.new(library_name, 0, [], 0, '')

    # 6.
    library.object_file_ids << objc_file_id
  
    # 7.
    @library_map[library_name] = library
  elsif line =~ /\[(.*)\]\s*([\w\s]+)/
    # Sample:
    # [  0] linker synthesized
    # [  1] dtrace

    # 1.
    objc_file_id = $1.to_i

    # 2.
    of = ObjectFile.new(
      objc_file_id,
      $2,
      '', 
      false,
      Array.new,
      0,
      0
    )

    # 3.
    @object_map[objc_file_id] = of
  end
end

#parse_sections(line) ⇒ Object



250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/fastlane/plugin/analyze_ios_linkmap/helper/analyze_ios_linkmap_helper.rb', line 250

def parse_sections(line)
  # Sections:
  # Address	    Size    	  Segment	  Section
  # 0x1000048A0	0x055656A8	__TEXT	  __text
  # 0x105569F48	0x000090E4	__TEXT	  __stubs
  # 0x10557302C	0x000079D4	__TEXT	  __stub_helper
  # 0x10557AA00	0x002D4E1A	__TEXT	  __cstring
  #
  
  lines = line.split(' ').each(&:strip)
  section_name = lines[3]
  segment_name = lines[2]
  start_addr = lines.first.to_i(16)
  end_addr = start_addr + lines[1].to_i(16)
  residual_size = lines[1].to_i(16)
  
  section = Section.new(
    section_name, 
    segment_name,
    start_addr,
    end_addr,
    0,
    residual_size
  )

  # 【section name】may be dulicate in different segment
  # 所以使用 segment_name + section_name 作为 map 的 key 存储
  @section_map[section.key] = section
end

#parse_symbols(line) ⇒ Object



280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/fastlane/plugin/analyze_ios_linkmap/helper/analyze_ios_linkmap_helper.rb', line 280

def parse_symbols(line)
  # Symbols:
  # Address	    Size    	  File    Name
  # 0x1000048A0	0x000000A4	[  2]   _main
  # 0x100004944	0x00000028	[  5]   _Bangcle_WB_AES_encrypt
  
  if line =~ %r(^0x(.+?)\s+0x(.+?)\s+\[(.+?)\]\s(.*))
    # 1.
    symbol_address = $1.to_i(16)  #=> Address
    symbol_size = $2.to_i(16)     #=> Size
    object_file_id = $3.to_i      #=> File
    symbol_name = $4              #=> Name
  
    # 2.
    object_file = @object_map[object_file_id]
    
    # 3.
    unless object_file
      UI.error "#{line.inspect} can not found object file"
      return
    end

    # 4.
    symbol = Symbol.new(
      symbol_address,
      symbol_size,
      object_file_id,
      symbol_name
    )

    # 5. 追加【symbol】符号
    object_file.symbols.push(symbol)

    # 6. 统计【Object File】总大小
    object_file.size += symbol_size

    # 7. 统计【library/framework】总大小
    library = @library_map[object_file.library]
    library.size += symbol_size if library

    # 8. 统计【segment】总大小
    sections = @section_map.detect do |seg_sec_name, sec|
      if sec
        (sec.start_addr...sec.end_addr).include?(symbol_address)
      else
        false
      end
    end
    # pp "⚠️ seg_sec_names=#{seg_sec_names}"

    if sections
      section = sections[1]
      segment_name = section.parse_segment
      segment = @segment_map[segment_name]
      # pp "⚠️ segment_name=#{segment_name}"

      unless segment
        segment = Segment.new(segment_name, symbol_size, symbol_size)
      else
        segment.symbol_size += symbol_size
        segment.residual_size += symbol_size
      end
      # pp "⚠️ #{segment.name} #{segment.symbol_size} - #{segment.residual_size}"
      @segment_map[segment_name] = segment
    end
  else
    UI.error "#{line.inspect} can not match symbol regular"
  end
end

#pretty_hashObject



385
386
387
388
389
390
# File 'lib/fastlane/plugin/analyze_ios_linkmap/helper/analyze_ios_linkmap_helper.rb', line 385

def pretty_hash
  UI.user_error!("#{@filepath} not pass")  unless @filepath
  UI.user_error!("#{@filepath} not exist") unless File.exist?(@filepath)

  result
end

#pretty_jsonObject



377
378
379
380
381
382
383
# File 'lib/fastlane/plugin/analyze_ios_linkmap/helper/analyze_ios_linkmap_helper.rb', line 377

def pretty_json
  result = pretty_hash
  unless result
    UI.user_error!("❌ LinkMap parsed failed!")
  end
  JSON.pretty_generate(result)
end

#resultObject



392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
# File 'lib/fastlane/plugin/analyze_ios_linkmap/helper/analyze_ios_linkmap_helper.rb', line 392

def result
  # 1. cache
  return @result if @result

  # 2. sort object_map[i].ObjectFile.symbols
  @object_map.each do |ofid, object|
    next unless object.symbols
  
    object.symbols.sort! do |sym1, sym2|
      sym2[:size] <=> sym1[:size]
    end
  end

  # 3. linkmap.txt 所有的 symbol 总大小
  total_size = @library_map.values.map(&:size).inject(:+)
  total_dead_size = @library_map.values.map(&:dead_symbol_size).inject(:+)

  # 4. 
  library_map_values = @library_map.values.sort do |a, b|
    b.size <=> a.size
  end
  library_map_values.compact!

  # 5. 
  library_maps = library_map_values.map do |lib|
    pod_name = lib.name
    unless lib.pod_name.empty?
      pod_name = lib.pod_name
    end
    # pp "pod_name=#{pod_name}"

    {
      library: lib.name,
      pod: pod_name,
      total: lib.size,
      format_total: Fastlane::Helper::LinkMap::FileHelper.format_size(lib.size),
      total_dead: lib.dead_symbol_size,
      format_total_dead: Fastlane::Helper::LinkMap::FileHelper.format_size(lib.dead_symbol_size),
      objects: lib.object_file_ids.map do |object_file_id|
        # Struct.new(:file_id, :object, :library, :framework, :symbols, :size, :dead_symbol_size) 
        object_file = @object_map[object_file_id]
        if object_file
          {
            object: object_file.object,
            symbols: object_file.symbols.map do |symb|
              {
                name: symb.name,
                total: symb.size,
                format_total: Fastlane::Helper::LinkMap::FileHelper.format_size(symb.size),
              }
            end
          }
        else
          nil
        end
      end
    }
  end
  
  # 6.
  @result = {
    total: total_size,
    format_total: Fastlane::Helper::LinkMap::FileHelper.format_size(total_size),
    total_dead: total_dead_size,
    format_total_dead: Fastlane::Helper::LinkMap::FileHelper.format_size(total_dead_size),
    librarys: library_maps
  }
  @result
end