Skip to content

Commit 923eb78

Browse files
author
Maruan Sahyoun
committed
PDFBOX-6391: Clone shared objects only once when merging and splitting
Co-Authored-By: Claude <noreply@anthropic.com> git-svn-id: https://svn.apache.org/repos/asf/pdfbox/trunk@1941424 13f79535-47bb-0310-9956-ffa450edef68
1 parent eae91d0 commit 923eb78

4 files changed

Lines changed: 188 additions & 4 deletions

File tree

‎pdfbox/src/main/java/org/apache/pdfbox/multipdf/PDFCloneUtility.java‎

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,10 @@
1919
import java.io.IOException;
2020
import java.io.InputStream;
2121
import java.io.OutputStream;
22+
import java.util.Arrays;
2223
import java.util.HashMap;
2324
import java.util.HashSet;
25+
import java.util.List;
2426
import java.util.Map;
2527
import java.util.Set;
2628
import org.apache.logging.log4j.Logger;
@@ -194,20 +196,42 @@ private COSDictionary cloneCOSDictionary(COSDictionary dictionary) throws IOExce
194196
* @throws IOException if an I/O error occurs
195197
*/
196198
void cloneMerge(final COSObjectable base, COSObjectable target) throws IOException
199+
{
200+
cloneMerge(base, target, new HashSet<>());
201+
}
202+
203+
/**
204+
* Merges two objects, see {@link #cloneMerge(COSObjectable, COSObjectable)}.
205+
*
206+
* @param base the base object to be cloned
207+
* @param target the merge target
208+
* @param merged all pairs of source and target arrays and dictionaries which were already
209+
* merged, each pair is merged only once
210+
* @throws IOException if an I/O error occurs
211+
*/
212+
private void cloneMerge(final COSObjectable base, COSObjectable target,
213+
Set<List<COSBase>> merged) throws IOException
197214
{
198215
if (base == null || base == target)
199216
{
200217
return;
201218
}
202-
cloneMergeCOSBase(base.getCOSObject(), target.getCOSObject());
219+
cloneMergeCOSBase(base.getCOSObject(), target.getCOSObject(), merged);
203220
}
204221

205-
private void cloneMergeCOSBase(final COSBase source, final COSBase target) throws IOException
222+
private void cloneMergeCOSBase(final COSBase source, final COSBase target,
223+
Set<List<COSBase>> merged) throws IOException
206224
{
207225
COSBase sourceBase = source instanceof COSObject ? ((COSObject) source).getObject()
208226
: source;
209227
COSBase targetBase = target instanceof COSObject ? ((COSObject) target).getObject()
210228
: target;
229+
if ((sourceBase instanceof COSArray || sourceBase instanceof COSDictionary)
230+
&& !merged.add(Arrays.asList(sourceBase, targetBase)))
231+
{
232+
// shared objects would be merged again and again, cycles endlessly
233+
return;
234+
}
211235
if (sourceBase instanceof COSArray && targetBase instanceof COSArray)
212236
{
213237
COSArray array = (COSArray) sourceBase;
@@ -227,7 +251,7 @@ else if (sourceBase instanceof COSDictionary && targetBase instanceof COSDiction
227251
COSBase value = entry.getValue();
228252
if (targetDict.getItem(key) != null)
229253
{
230-
cloneMerge(value, targetDict.getItem(key));
254+
cloneMerge(value, targetDict.getItem(key), merged);
231255
}
232256
else
233257
{

‎pdfbox/src/main/java/org/apache/pdfbox/multipdf/Splitter.java‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
import java.io.IOException;
2020
import java.util.ArrayList;
21+
import java.util.Arrays;
2122
import java.util.Collections;
2223
import java.util.HashMap;
2324
import java.util.HashSet;
@@ -565,6 +566,14 @@ else if (actualSrcObj instanceof COSDictionary)
565566
*/
566567
private class KCloner
567568
{
569+
/**
570+
* Clones of arrays and dictionaries without clone, for the source, the destination parent
571+
* and the current page. Shared arrays and dictionaries would otherwise be cloned again for
572+
* each reference.
573+
*/
574+
private final Map<List<COSBase>, COSBase> arrayClones = new HashMap<>();
575+
private final Set<List<COSBase>> dictionariesWithoutClone = new HashSet<>();
576+
568577
/**
569578
* Creates a clone of the source.
570579
*
@@ -593,6 +602,13 @@ else if (src instanceof COSDictionary)
593602

594603
private COSBase createArrayClone(COSBase src, COSBase dstParent, COSDictionary currentPageDict)
595604
{
605+
List<COSBase> key = Arrays.asList(src, dstParent, currentPageDict);
606+
if (arrayClones.containsKey(key))
607+
{
608+
// null while the array is being cloned, i.e. for a cycle
609+
return arrayClones.get(key);
610+
}
611+
arrayClones.put(key, null);
596612
COSArray dst = new COSArray();
597613
for (COSBase base2 : (COSArray) src)
598614
{
@@ -611,7 +627,9 @@ private COSBase createArrayClone(COSBase src, COSBase dstParent, COSDictionary c
611627
dst.add(rc);
612628
}
613629
}
614-
return dst.isEmpty() ? null : dst;
630+
COSBase clone = dst.isEmpty() ? null : dst;
631+
arrayClones.put(key, clone);
632+
return clone;
615633
}
616634

617635
private COSBase createDictionaryClone(COSBase src, COSBase dstParent, COSDictionary currentPageDict)
@@ -622,6 +640,11 @@ private COSBase createDictionaryClone(COSBase src, COSBase dstParent, COSDiction
622640
{
623641
return dstDict;
624642
}
643+
List<COSBase> cloneKey = Arrays.asList(srcDict, dstParent, currentPageDict);
644+
if (dictionariesWithoutClone.contains(cloneKey))
645+
{
646+
return null;
647+
}
625648
COSDictionary srcPageDict = srcDict.getCOSDictionary(COSName.PG);
626649
COSDictionary dstPageDict = null;
627650
COSBase kid = srcDict.getDictionaryObject(COSName.K);
@@ -701,6 +724,7 @@ else if (srcObj != null) // 079177.pdf
701724
if (cloneKid == null && kid != null)
702725
{
703726
structDictMap.remove(srcDict);
727+
dictionariesWithoutClone.add(cloneKey);
704728
return null; // kids array wasn't empty, but is empty now => ignore
705729
}
706730

@@ -711,6 +735,7 @@ else if (srcObj != null) // 079177.pdf
711735
{
712736
// if no parent page and no page here and no kids, assume this is an orphan
713737
structDictMap.remove(srcDict);
738+
dictionariesWithoutClone.add(cloneKey);
714739
return null;
715740
}
716741
dstDict.setItem(COSName.K, cloneKid);

‎pdfbox/src/test/java/org/apache/pdfbox/multipdf/PDFCloneUtilityTest.java‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
import static org.junit.jupiter.api.Assertions.assertEquals;
1919
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
20+
import static org.junit.jupiter.api.Assertions.assertSame;
2021

2122
import java.awt.Color;
2223
import java.io.ByteArrayOutputStream;
@@ -26,7 +27,9 @@
2627

2728
import org.apache.pdfbox.pdmodel.PDDocument;
2829
import org.apache.pdfbox.Loader;
30+
import org.apache.pdfbox.cos.COSArray;
2931
import org.apache.pdfbox.cos.COSDictionary;
32+
import org.apache.pdfbox.cos.COSInteger;
3033
import org.apache.pdfbox.cos.COSName;
3134
import org.apache.pdfbox.cos.COSObject;
3235
import org.apache.pdfbox.pdmodel.PDPage;
@@ -164,4 +167,47 @@ void testDirectIndirect() throws IOException
164167
}
165168
}
166169
}
170+
171+
/**
172+
* Source and target have 20 levels of dictionaries, each with two entries pointing to the same
173+
* dictionary of the next level. The shared dictionaries must be merged only once.
174+
*
175+
* @throws IOException
176+
*/
177+
@Test
178+
void testCloneMergeSharedDictionaries() throws IOException
179+
{
180+
try (PDDocument doc = new PDDocument())
181+
{
182+
COSArray targetLeaf = new COSArray();
183+
targetLeaf.add(COSInteger.ONE);
184+
COSDictionary target = createSharedDictionaries(20, targetLeaf);
185+
COSArray sourceLeaf = new COSArray();
186+
sourceLeaf.add(COSInteger.TWO);
187+
COSDictionary source = createSharedDictionaries(20, sourceLeaf);
188+
189+
new PDFCloneUtility(doc).cloneMerge(source, target);
190+
191+
assertEquals(2, targetLeaf.size());
192+
assertSame(COSInteger.TWO, targetLeaf.get(1));
193+
}
194+
}
195+
196+
/**
197+
* Creates the given number of levels of dictionaries, the entries /A and /B of each one point to
198+
* the dictionary of the next level. The last one contains the given array as /Leaf.
199+
*/
200+
private static COSDictionary createSharedDictionaries(int levels, COSArray leaf)
201+
{
202+
COSDictionary dict = new COSDictionary();
203+
dict.setItem(COSName.getPDFName("Leaf"), leaf);
204+
for (int i = 0; i < levels; i++)
205+
{
206+
COSDictionary parent = new COSDictionary();
207+
parent.setItem(COSName.A, dict);
208+
parent.setItem(COSName.B, dict);
209+
dict = parent;
210+
}
211+
return dict;
212+
}
167213
}

‎pdfbox/src/test/java/org/apache/pdfbox/multipdf/SplitterTest.java‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,18 @@
1818
import java.io.ByteArrayOutputStream;
1919
import java.io.File;
2020
import java.io.IOException;
21+
import java.lang.management.ManagementFactory;
2122
import java.util.ArrayList;
2223
import java.util.Collections;
2324
import java.util.LinkedHashMap;
2425
import java.util.List;
2526
import java.util.Map;
2627

2728
import org.apache.pdfbox.Loader;
29+
import org.apache.pdfbox.cos.COSArray;
30+
import org.apache.pdfbox.cos.COSBase;
2831
import org.apache.pdfbox.cos.COSDictionary;
32+
import org.apache.pdfbox.cos.COSInteger;
2933
import org.apache.pdfbox.cos.COSName;
3034
import org.apache.pdfbox.io.IOUtils;
3135
import org.apache.pdfbox.pdmodel.PDDestinationNameTreeNode;
@@ -53,6 +57,7 @@
5357
import static org.junit.jupiter.api.Assertions.assertSame;
5458
import static org.junit.jupiter.api.Assertions.assertThrows;
5559
import static org.junit.jupiter.api.Assertions.assertTrue;
60+
import static org.junit.jupiter.api.Assumptions.assumeTrue;
5661
import org.junit.jupiter.api.Test;
5762
import org.junit.jupiter.api.parallel.Execution;
5863
import org.junit.jupiter.api.parallel.ExecutionMode;
@@ -686,4 +691,88 @@ void testSplitterCanBeReused() throws IOException
686691
}
687692

688693
// End Claude Sonnet 5.5 generated tests
694+
695+
/**
696+
* A structure tree with 18 levels of arrays, each containing the array of the next level twice,
697+
* and 18 levels of structure elements, each with the structure element of the next level twice
698+
* in its /K array. The structure elements belong to the second page only. Shared arrays and
699+
* structure elements which aren't part of a split document must not be cloned again for each
700+
* reference.
701+
*
702+
* @throws IOException
703+
*/
704+
@Test
705+
void testSplitWithSharedStructureElements() throws IOException
706+
{
707+
assumeTrue(ManagementFactory.getThreadMXBean() instanceof com.sun.management.ThreadMXBean);
708+
com.sun.management.ThreadMXBean threadBean =
709+
(com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
710+
assumeTrue(threadBean.isThreadAllocatedMemorySupported());
711+
threadBean.setThreadAllocatedMemoryEnabled(true);
712+
// load and initialize the classes first
713+
splitSharedStructure(1);
714+
715+
long threadId = Thread.currentThread().getId();
716+
long allocatedBefore = threadBean.getThreadAllocatedBytes(threadId);
717+
splitSharedStructure(18);
718+
long allocated = threadBean.getThreadAllocatedBytes(threadId) - allocatedBefore;
719+
assertTrue(allocated < 16 * 1024 * 1024, allocated + " bytes allocated");
720+
}
721+
722+
private static void splitSharedStructure(int levels) throws IOException
723+
{
724+
try (PDDocument doc = new PDDocument())
725+
{
726+
PDPage page1 = new PDPage();
727+
PDPage page2 = new PDPage();
728+
doc.addPage(page1);
729+
doc.addPage(page2);
730+
731+
COSArray array = new COSArray();
732+
array.add(createStructureElement(COSName.P, page1, COSInteger.ZERO));
733+
for (int i = 0; i < levels; i++)
734+
{
735+
COSArray parent = new COSArray();
736+
parent.add(array);
737+
parent.add(array);
738+
array = parent;
739+
}
740+
741+
COSDictionary element = createStructureElement(COSName.P, page2, COSInteger.ZERO);
742+
for (int i = 0; i < levels; i++)
743+
{
744+
COSArray kids = new COSArray();
745+
kids.add(element);
746+
kids.add(element);
747+
element = createStructureElement(COSName.getPDFName("Div"), null, kids);
748+
}
749+
750+
COSArray k = new COSArray();
751+
k.add(array);
752+
k.add(element);
753+
PDStructureTreeRoot structureTreeRoot = new PDStructureTreeRoot();
754+
structureTreeRoot.setK(k);
755+
doc.getDocumentCatalog().setStructureTreeRoot(structureTreeRoot);
756+
757+
List<PDDocument> splitResult = new Splitter().split(doc);
758+
assertEquals(2, splitResult.size());
759+
for (PDDocument splitDoc : splitResult)
760+
{
761+
splitDoc.close();
762+
}
763+
}
764+
}
765+
766+
private static COSDictionary createStructureElement(COSName type, PDPage page, COSBase kids)
767+
{
768+
COSDictionary element = new COSDictionary();
769+
element.setItem(COSName.TYPE, COSName.getPDFName("StructElem"));
770+
element.setItem(COSName.S, type);
771+
if (page != null)
772+
{
773+
element.setItem(COSName.PG, page);
774+
}
775+
element.setItem(COSName.K, kids);
776+
return element;
777+
}
689778
}

0 commit comments

Comments
 (0)