evanphx / rubinius

Rubinius, the Ruby VM

This URL has Read+Write access

rubinius / kernel / compiler / compiled_file.rb
100644 359 lines (306 sloc) 8.721 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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
113
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
249
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
279
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
349
350
351
352
353
354
355
356
357
358
359
module Rubinius
  ##
  # A decode for the .rbc file format.
 
  class CompiledFile
    ##
    # Create a CompiledFile with +magic+ magic bytes, of version +ver+,
    # data containing a SHA1 sum of +sum+. The optional +stream+ is used
    # to lazy load the body.
 
    def initialize(magic, ver, sum, stream=nil)
      @magic, @version, @sum = magic, ver, sum
      @stream = stream
      @data = nil
    end
 
    attr_reader :magic
    attr_reader :version
    attr_reader :sum
    attr_reader :stream
 
    ##
    # From a stream-like object +stream+ load the data in and return a
    # CompiledFile object.
 
    def self.load(stream)
      raise IOError, "attempted to load nil stream" unless stream
 
      magic = stream.gets.strip
      version = Integer(stream.gets.strip)
      sum = stream.gets.strip
 
      return new(magic, version, sum, stream)
    end
 
    ##
    # Writes the CompiledFile +cm+ to +file+.
    def self.dump(cm, file)
      File.open(file, "w") do |f|
        new("!RBIX", 0, "x").encode_to(f, cm)
      end
    rescue Errno::EACCES
      # just skip writing the compiled file if we don't have permissions
    end
 
    ##
    # Encode the contets of this CompiledFile object to +stream+ with
    # a body of +body+. Body use marshalled using CompiledFile::Marshal
 
    def encode_to(stream, body)
      stream.puts @magic
      stream.puts @version.to_s
      stream.puts @sum.to_s
 
      mar = CompiledFile::Marshal.new
      stream << mar.marshal(body)
    end
 
    ##
    # Return the body object by unmarshaling the data
 
    def body
      return @data if @data
 
      mar = CompiledFile::Marshal.new
      @data = mar.unmarshal(stream)
    end
 
    ##
    # A class used to convert an CompiledMethod to and from
    # a String.
 
    class Marshal
 
      ##
      # Read all data from +stream+ and invoke unmarshal_data
 
      def unmarshal(stream)
        if stream.kind_of? String
          str = stream
        else
          str = stream.read
        end
 
        @start = 0
        @size = str.size
        @data = str.data
 
        unmarshal_data
      end
 
      ##
      # Process a stream object +stream+ as as marshalled data and
      # return an object representation of it.
 
      def unmarshal_data
        kind = next_type
        case kind
        when ?t
          return true
        when ?f
          return false
        when ?n
          return nil
        when ?I
          return read_varint
        when ?J
          return -read_varint
        when ?d
          str = next_string.chop
 
          # handle the special NaN, Infinity and -Infinity differently
          if str[0] == ?\ # leading space
            x = str.to_f
            e = str[-5..-1].to_i
 
            # This is necessary because (2**1024).to_f yields Infinity
            if e == 1024
              return x * 2 ** 512 * 2 ** 512
            else
              return x * 2 ** e
            end
          else
            case str.downcase
            when "infinity"
              return 1.0 / 0.0
            when "-infinity"
              return -1.0 / 0.0
            when "nan"
              return 0.0 / 0.0
            else
              raise TypeError, "Invalid Float format: #{str}"
            end
          end
        when ?s
          count = read_varint
          str = next_bytes count
          return str
        when ?x
          count = read_varint
          str = next_bytes count
          return str.to_sym
        when ?S
          count = read_varint
          str = next_bytes count
          return SendSite.new(str.to_sym)
        when ?p
          count = read_varint
          obj = Tuple.new(count)
          i = 0
          while i < count
            obj[i] = unmarshal_data
            i += 1
          end
          return obj
        when ?i
          count = read_varint
          seq = InstructionSequence.new(count)
          i = 0
          while i < count
            seq[i] = read_varint
            i += 1
          end
          return seq
        when ?M
          version = read_varint
          if version != 1
            raise "Unknown CompiledMethod version #{version}"
          end
          cm = CompiledMethod.new
          cm.__ivars__ = unmarshal_data
          cm.primitive = unmarshal_data
          cm.name = unmarshal_data
          cm.iseq = unmarshal_data
          cm.stack_size = unmarshal_data
          cm.local_count = unmarshal_data
          cm.required_args = unmarshal_data
          cm.total_args = unmarshal_data
          cm.splat = unmarshal_data
          cm.literals = unmarshal_data
          cm.exceptions = unmarshal_data
          cm.lines = unmarshal_data
          cm.file = unmarshal_data
          cm.local_names = unmarshal_data
          return cm
        else
          raise "Unknown type '#{kind.chr}'"
        end
      end
 
      private :unmarshal_data
 
      ##
      # Returns the next character in _@data_ as a Fixnum.
      #--
      # The current format uses a one-character type indicator
      # followed by a newline. If that format changes, this
      # will break and we'll fix it.
      #++
      def next_type
        chr = @data[@start]
        @start += 1
        chr
      end
 
      private :next_type
 
      ##
      # Returns the next string in _@data_ including the trailing
      # "\n" character.
      def next_string
        count = @data.locate "\n", @start
        count = @size unless count
        str = String.from_bytearray @data, @start, count - @start
        @start = count
        str
      end
 
      private :next_string
 
      ##
      # Returns the next _count_ bytes in _@data_.
      def next_bytes(count)
        str = String.from_bytearray @data, @start, count
        @start += count
        str
      end
 
      private :next_bytes
 
      ##
      # Returns the next byte in _@data_.
      def next_byte
        byte = @data[@start]
        @start += 1
        byte
      end
 
      private :next_byte
 
      ##
      # For object +val+, return a String represetation.
 
      def marshal(val)
        str = ""
 
        case val
        when TrueClass
          str << "t"
        when FalseClass
          str << "f"
        when NilClass
          str << "n"
        when Fixnum, Bignum
          if val < 0
            str << 'J' << to_varint(-val)
          else
            str << 'I' << to_varint(val)
          end
        when String
          str << "s#{to_varint(val.size)}#{val}"
        when Symbol
          s = val.to_s
          str << "x#{to_varint(s.size)}#{s}"
        when SendSite
          s = val.name.to_s
          str << "S#{to_varint(s.size)}#{s}"
        when Tuple
          str << "p#{to_varint(val.size)}"
          val.each do |ele|
            str << marshal(ele)
          end
        when Float
          str << "d"
          if val.infinite?
            str << "-" if val < 0.0
            str << "Infinity"
          elsif val.nan?
            str << "NaN"
          else
            str << " %+.54f %5d" % Math.frexp(val)
          end
          str << "\n"
        when InstructionSequence
          str << "i#{to_varint(val.size)}"
          val.opcodes.each do |op|
            str << to_varint(op)
          end
        when CompiledMethod
          str << "M#{to_varint(1)}"
          str << marshal(val.__ivars__)
          str << marshal(val.primitive)
          str << marshal(val.name)
          str << marshal(val.iseq)
          str << marshal(val.stack_size)
          str << marshal(val.local_count)
          str << marshal(val.required_args)
          str << marshal(val.total_args)
          str << marshal(val.splat)
          str << marshal(val.literals)
          str << marshal(val.exceptions)
          str << marshal(val.lines)
          str << marshal(val.file)
          str << marshal(val.local_names)
        else
          raise ArgumentError, "Unknown type #{val.class}: #{val.inspect}"
        end
 
        return str
      end
 
      ##
      # Encodes a positive integer as an unsigned varint.
      def to_varint(val)
        return "\0" if val == 0
 
        buf = ''
 
        while val > 0
          x = val & 127
 
          if val > 127
            x |= 128
          end
 
          val >>= 7
 
          buf << x
        end
 
        buf
      end
 
      private :to_varint
 
      ##
      # Decodes an unsigned varint to a positive integer.
      def read_varint
        val = 0
        shift = 0
 
        loop do
          byte = next_byte
 
          val += (byte & ~128) << shift
          break if byte < 128
 
          shift += 7
        end
 
        val
      end
 
      private :read_varint
    end
  end
end