summaryrefslogtreecommitdiffstats
path: root/jack/src/com/android/jack/shrob/obfuscation/resource/RefinedVFile.java
blob: dd2e2d5c788f44dd3469ca35d127c3d9f1fc6637 (plain)
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
/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.jack.shrob.obfuscation.resource;

import com.android.sched.util.file.CannotDeleteFileException;
import com.android.sched.util.file.WrongPermissionException;
import com.android.sched.util.location.Location;
import com.android.sched.vfs.AbstractVElement;
import com.android.sched.vfs.InputVFile;
import com.android.sched.vfs.VPath;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

import javax.annotation.CheckForNull;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;

/**
 * A {@code VFile} wrapping another {@code VFile} with refining data.
 */
public class RefinedVFile extends AbstractVElement implements InputVFile {

  @Nonnull
  private final InputVFile file;

  @Nonnull
  private final TreeSet<RefinedEntry> refinedEntries =
      new TreeSet<RefinedVFile.RefinedEntry>(new Comparator<RefinedEntry>() {

        @Override
        public int compare(@Nonnull RefinedEntry e1, @Nonnull RefinedEntry e2) {
          return e1.startPosition > e2.startPosition ? 1
              : (e1.endPosition < e2.startPosition ? -1 : 0);
        }

      });

  public RefinedVFile(@Nonnull InputVFile file) {
    this.file = file;
  }

  public void addRefinedEntry(@Nonnegative int startPosition, @Nonnegative int endPosition,
      @Nonnull CharSequence content) {
    refinedEntries.add(new RefinedEntry(startPosition, endPosition, content));
  }

  @Nonnull
  @Override
  public InputStream getInputStream() throws WrongPermissionException {
    InputStream inputStream = file.getInputStream();
    if (refinedEntries.isEmpty()) {
      return inputStream;
    }
    return new RefinedInputStream(inputStream);
  }

  @Nonnull
  @Override
  public String getName() {
    return file.getName();
  }

  @Override
  @Nonnull
  public Location getLocation() {
    return file.getLocation();
  }

  @Override
  public boolean isVDir() {
    return false;
  }

  private static class RefinedEntry {
    @Nonnegative
    private final int startPosition;

    @Nonnegative
    private final int endPosition;

    @Nonnull
    private final CharSequence content;

    private RefinedEntry(@Nonnegative int startPosition, @Nonnegative int endPosition,
        @Nonnull CharSequence content) {
      this.startPosition = startPosition;
      this.endPosition = endPosition;
      this.content = content;
    }

    @Nonnull
    public InputStream openRead() {
      return new ByteArrayInputStream(content.toString().getBytes());
    }

    @Override
    public String toString() {
      return startPosition + ":" + endPosition;
    }
  }

  private class RefinedInputStream extends InputStream {

    /**
     * The unrefined inputstream
     */
    @Nonnull
    private final InputStream baseInputStream;

    /**
     * The position in the baseInputStream
     */
    private int position = -1;

    /**
     * The current refined part of the stream
     */
    @CheckForNull
    private InputStream currentStream;

    /**
     * Current or next refined entry that we are reading or will be reading.
     */
    @CheckForNull
    private RefinedEntry currentRefinedEntry;

    /**
     * Iterator representing the position in the refinedEntries. Entries before this iterator have
     * already been read.
     */
    @Nonnull
    private final Iterator<RefinedEntry> refinedEntryIterator;

    public RefinedInputStream(@Nonnull InputStream baseInputStream) {
      this.baseInputStream = baseInputStream;
      refinedEntryIterator = RefinedVFile.this.refinedEntries.iterator();
      if (refinedEntryIterator.hasNext()) {
        currentRefinedEntry = refinedEntryIterator.next();
      }
    }

    @Override
    public int read() throws IOException {
      int inputData;
      if (currentStream != null) {
        // We are reading a refined entry
        inputData = currentStream.read();
        if (inputData == -1) {
          // The entry has already been completely read
          closeCurrentRefinedEntry();
        } else {
          return inputData;
        }
      }
      if (openNextRefinedEntryIfNecessary()) {
        assert currentStream != null;
        return currentStream.read();
      }
      // No refined entry was found, read the base stream normally.
      position++;
      return baseInputStream.read();
    }

    private boolean openNextRefinedEntryIfNecessary() {
      // Check that previous refined entry was completely read
      assert currentStream == null;
      if (currentRefinedEntry != null) {
        if (currentRefinedEntry.startPosition <= position + 1) {
          assert currentRefinedEntry.endPosition >= position;
          // A refined entry should be read
          currentStream = currentRefinedEntry.openRead();
          return true;
        }
      }
      return false;
    }

    private void closeCurrentRefinedEntry() throws IOException {
      // Reset current stream
      assert currentStream != null;
      currentStream.close();
      currentStream = null;

      assert currentRefinedEntry != null;
      // Set the base inputstream position to the refined entry end position
      int toSkip = currentRefinedEntry.endPosition - position;
      while (toSkip > 0) {
        assert baseInputStream.available() != 0;
        toSkip -= baseInputStream.skip(toSkip);
      }
      position = currentRefinedEntry.endPosition;

      // Next refined entry
      if (refinedEntryIterator.hasNext()) {
        currentRefinedEntry = refinedEntryIterator.next();
      } else {
        currentRefinedEntry = null;
      }
    }


    @Override
    public int read(byte[] b, int off, int len) throws IOException {
      if (available() == 0) {
        return -1;
      }

      int totalRead = 0;
      while (available() != 0 && totalRead < len) {
        // Read current refined entry if any
        if (currentStream != null) {
          totalRead += currentStream.read(b, off + totalRead, len - totalRead);
          if (currentStream.available() == 0) {
            closeCurrentRefinedEntry();
          }
        }

        // Read until next refined entry
        // Calculate the length of bytes that can be read without refining
        int baseLength;
        if (currentRefinedEntry != null) {
          baseLength =
              Math.min(currentRefinedEntry.startPosition - (position + 1), len - totalRead);
        } else {
          baseLength = len - totalRead;
        }
        int read = baseInputStream.read(b, off + totalRead, baseLength);
        totalRead += read;
        position += read;

        if (totalRead < len) {
          openNextRefinedEntryIfNecessary();
        }
      }

      return totalRead;
    }

    @Override
    public int available() throws IOException {
      int available = 0;
      if (currentStream != null) {
        available += currentStream.available();
      }
      if (baseInputStream.available() > 0) {
        available += 1;
      }
      return available;
    }

    @Override
    public void close() throws IOException {
      super.close();
      baseInputStream.close();
    }
  }

  @Override
  public void delete() throws CannotDeleteFileException {
    file.delete();
  }

  @Override
  @Nonnull
  public VPath getPathFromRoot() {
    return file.getPathFromRoot();
  }

  @Override
  public long getLastModified() {
    return file.getLastModified();
  }
}